https://leetcode.com/problems/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?
1. brute force,每遇到一个数都遍历数组剩下的数,时间复杂度O(n^2)
2. hashtable,时间复杂度O(n), 空间复杂度O(n)
3. 排序,时间复杂度O(n*lgn),空间复杂度O(1)
3. 异或,两个相同的数异或就是0,任何数异或0都不变,所以异或到最后剩下的数就是只出现了一次的数。时间复杂度O(n),空间复杂度O(1)
public class Solution {
public int singleNumber(int[] A) {
int ans = A[0];
for(int i=1; i<A.length; i++){
ans ^= A[i];
}
return ans;
}
}
155

被折叠的 条评论
为什么被折叠?



