136.SingleNumber
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?
方法一:Time Limited
public int singleNumber(int[] nums) {
Arrays.sort(nums);
for(int i = 0; i < nums.length - 1; i =+ 2){
if(nums[i] != nums[i + 1])
return nums[i];
}
return nums[0];
}
方法二:Accepted
这里用到了异或的知识,原理:一个数和 0 异或结果是它本身,一个数和自己异或结果是 0 。
public int singleNumber2(int[] nums) {
int result = 0;
for(int i = 0; i < nums.length; i++){
result ^= nums[i];
}
return result;
}
复杂度分析:
时间复杂度:O(n)
空间复杂度:O(1)
方法三:Accepted
利用 HashMap
public int singleNumber3(int[] nums){
int result = 0;
HashMap<Integer, Integer> table = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(!table.containsKey(nums[i])){
table.put(nums[i], nums[i]);
}
else{
table.remove(nums[i]);
}
}
for(Integer key : table.keySet()){
result = key;
}
return result;
}
复杂度分析:
时间复杂度:O(n)
空间复杂度:O(n)