美文网首页
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

    只出现一次的数字 我们可以考虑 异或运算 ,它是满足交换律和结合的,也就是说 abc = acb,这样当我们遍历数...

  • leetcode 初级之数组篇 01

    26. 删除排序数组中的重复项 两种方法的比较: 第一种方法,是前后两个元素是否相等,如果不等,将其存储到k所指示...

  • leetcode 初级之数组篇 04

    存在重复 给定一个整数数组,判断是否存在重复元素。 如果任何值在数组中出现至少两次,函数返回 true。如果数组中...

  • leetcode 初级之数组篇 06

    两个数组的交集 II 给定两个数组,编写一个函数来计算它们的交集。 示例 1: 输入: nums1 = [1,2,...

  • leetcode 初级之数组篇 03

    旋转数组 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。示例 1:输入: [1,2,3,4...

  • leetcode 初级之数组篇 10

    36.有效的数独 判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。 数字 1...

  • leetcode 初级之数组篇 02

    买卖股票的最佳时机 II 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。设计一个算法来计算你所能...

  • leetcode 初级之数组篇 08

    283. Move Zeroes 移动零给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持...

  • leetcode 初级之数组篇 07

    加一 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 最高位数字存放在数组的首位, 数组中每个...

  • leetcode 初级之数组篇 09

    两数之和 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的...

网友评论

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

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