[LeetCode]136. Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

题目

给定一个整数数组,里面只有一个数只出现一次,其余的数都出现两次,找出只出现一次的数。

方法

采用异或运算^
a ^ a = 0
a ^ 0 = a
a ^ b ^ c = a ^ (b ^ c)

c代码

#include <assert.h>

int singleNumber(int* nums, int numsSize) {
    int i = 0;
    int single = 0;
    for(i = 0; i < numsSize; i++) {
        single ^= nums[i];
    }
    return single;
}

int main() {
    int nums[5] = {1,3,3,1,5};
    assert(singleNumber(nums, 5) == 5);

    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容