[LeetCode]Single Number
2014-06-26 22:46
323 查看
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?
Analysis:
The requirement is O(n) time and O(1) space.
Thus, the "first sort and then find " way is not working.
Also the "hash map" way is not working.
Since we can not sort the array, we shall find a cumulative way, which is not about the ordering.
XOR (Exclusiove Or) is a good way, we can use the property that A XOR A = 0, and A XOR B XOR A = B.
So, the code becomes extremely easy.
Java
c++
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Analysis:
The requirement is O(n) time and O(1) space.
Thus, the "first sort and then find " way is not working.
Also the "hash map" way is not working.
Since we can not sort the array, we shall find a cumulative way, which is not about the ordering.
XOR (Exclusiove Or) is a good way, we can use the property that A XOR A = 0, and A XOR B XOR A = B.
So, the code becomes extremely easy.
Java
public int singleNumber(int[] A) { int result = A[0]; for(int i=1;i<A.length;i++){ result = result^A[i]; } return result; }
c++
int singleNumber(int A[], int n) { int result = A[0]; for(int i=1;i<n;i++){ result = result ^ A[i]; } return result; }
相关文章推荐
- LeetCode:Single Number
- Java [Leetcode 136]Single Number
- LeetCode 136 Single Number 出现一次的数字
- [leetcode] Single Number
- LeetCode136—Single Number
- 【leetcode】136. Single Number
- LeetCode: Single Number
- 【LeetCode】- Single Number(从数组中找出只出现一次的数字)
- Leetcode 位运算 Single Number
- leetcode-Single Number
- [LeetCode] Single Number
- leetcode-136-Single Number
- leetcode 136. Single Number
- 10--LeetCode【Single Number】|C语言|
- Leetcode:136. Single Number
- LeetCode 136 Single Number
- LeetCode ----Single Number 找出与众不同的数
- [leetcode-136]Single Number(c)
- 【Leetcode-easy-136】Single Number
- LeetCode | Single Number(数组中的单个数字)