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?

public class Solution {
    public int singleNumber(int[] A) {
        //a^b^c = a ^ ( b ^ c );
        //0 ^ a = a
        //a ^ a = 0
        //a ^ a ^ b ^ b ... ^ e ^... = e
        int c = A[0];
        for(int i = 1 ;i < A.length; i ++){
            c = c ^ A[i];
        }
        return c;
    }
}

Runtime: 384 ms

解法太巧妙了,服了。。。。

这道题如果没有限制条件的话,还是很简单的,最简单的用HashMap记录每一个元素出现的次数;或者用O(nlogn)的时间排序,找到A[A.length/2];

主要问题在于怎么在O(n)的时间内找到,自己的想法一直是在想怎么缩短排序的时间。

记得有一个交换两个数据的问题。

a 和b 交换,不能使用额外的空间

a ^= b;

b ^= a;

a ^= b;

你可能感兴趣的:(LeetCode,number,single)