Single Number 【leetcode】1分钟解题系类


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?


这个题目是做过的,之前跟王子讨论过2个不同的数字。其它都是两对相同的时候,想到了位运算这种巧妙的算法。

异或运算:相同为0,不同为1。把所有的数字都异或一遍,相同的数字异或就约掉了,只剩下那个不同的数字了。

(秒解)


class Solution {
public:
    int singleNumber(int A[], int n) {
        int result = 0;
        for(int i=0;i<n;i++){
            result=result^A[i];
        }
        return result;
    }
};


你可能感兴趣的:(LeetCode)