【03_136】Single Number

感谢:http://www.cnblogs.com/changchengxiao/p/3413294.html

Single Number

Total Accepted: 103007 Total Submissions: 217483 Difficulty: Medium

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?

琢磨了很久没找到满足题目的两个要求:O(1)和不开空间。实在没办法才上网查找,原来是汇编语言的知识,而且C++中还可以直接用。

原文:

o(n)的算法只能是线性扫描一遍,可能的相法是位运算。对于异或来说:

. 异或运算是可交换,即 a ^ b = b ^ a

.  ^ a = a

那么如果对所有元素做异或运算,其结果为那个出现一次的元素,理解是a1 ^ a2 ^ ....

所以说,这是终极解法。

 public class Solution {
public int singleNumber(int[] A) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(A == null || A.length == ){
return ;
}
int result = A[]; for(int i = ; i < A.length; i++){
result ^= A[i];
}
return result;
}
}

LeetCode很有趣,希望明天可以自己想出来!

上一篇:【LeetCode】Single Number I & II & III


下一篇:【leetcode】Single Number II