[LeetCode] - Single Number
2013-12-16 03:09
169 查看
Description: 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?
这是整个LeetCode上面做的第一道题。没啥好说的,XOR即可。
http://stackoverflow.com/questions/1089987/given-an-array-of-numbers-except-for-one-number-all-the-others-occur-twice-gi
Assuming you can
numbers, that is the key here, I believe, because of the following properties:
commutative and associative (so the order in which it's done is irrelevant).
a number
with itself will always be zero.
zero
with a number will be that number.
So, if you simply
the values together, all of the ones that occur twice will cancel each other out (giving 0) and the one remaining number (
will
that result (0) to give
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
这是整个LeetCode上面做的第一道题。没啥好说的,XOR即可。
public class Solution { public int singleNumber(int[] A) { int single = 0; for(int i=0; i < A.length; i++) { single ^= A[i]; } return single; } }
http://stackoverflow.com/questions/1089987/given-an-array-of-numbers-except-for-one-number-all-the-others-occur-twice-gi
Assuming you can
XORthe
numbers, that is the key here, I believe, because of the following properties:
XORis
commutative and associative (so the order in which it's done is irrelevant).
a number
XORed
with itself will always be zero.
zero
XORed
with a number will be that number.
So, if you simply
XORall
the values together, all of the ones that occur twice will cancel each other out (giving 0) and the one remaining number (
n)
will
XORwith
that result (0) to give
n.
相关文章推荐
- [LeetCode] 136. Single Number
- LeetCode-136.Single Number
- LeetCode——Single Number(找出数组中只出现一次的数)
- LeetCode 136 Single Number题解
- [LeetCode] [Single Number 2013-10-01]
- Leetcode Single Number
- LeetCode 136. Single Number
- LeetCode - Single Number
- leetcode :Single Number
- leetcode-Single Number
- LeetCode 136: Single Number
- LeetCode(4) -- Single Number
- leetcode 136. Single Number
- leetcode——136——Single Number
- leetcode 136. Single Number
- [LeetCode]Single Number
- leetcode single number系列
- LeetCode 136 : Single Number
- leetcode - Single Number
- 【leetcode】Single Number (java)