美文网首页
leetcode 初级之数组篇 05

leetcode 初级之数组篇 05

作者: ngugg | 来源:发表于2018-09-14 20:20 被阅读0次

    只出现一次的数字

    我们可以考虑 异或运算 ,它是满足交换律和结合的,也就是说 abc = acb,这样当我们遍历数组,顺次进行异或运算,那么最终的结果就是唯一的不重复数字。
    Let us consider the above example.
    Let ^ be xor operator as in C and C++.
    //
    //res = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4
    //
    //Since XOR is associative and commutative, above
    //expression can be written as:
    //res = 7 ^ (3 ^ 3) ^ (4 ^ 4) ^ (5 ^ 5)
    //= 7 ^ 0 ^ 0 ^ 0
    //= 7 ^ 0
    //= 7

    执行耗时 4ms, 战胜100% 的提交

    int singleNumber(int* nums, int numsSize) {
        int result = nums[0];
        for (int i = 1; i < numsSize; i++) {
            result ^= nums[i];
        }
        return result;
    }
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            int arr[] = {1,1,2,3,2};
            int a = singleNumber(arr, 5);
            printf("%d\n",a);
            
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:leetcode 初级之数组篇 05

          本文链接:https://www.haomeiwen.com/subject/vvdagftx.html