https://leetcode-cn.com/problems/single-number/
1、使用HashMap
public int singleNumber(int[] nums) {
HashMap hashMap = new HashMap();
for(int x:nums) {
hashMap.put(x, (int)hashMap.getOrDefault(x, 0) + 1);
}
for(int y:(Set<Integer>)hashMap.keySet()) {
if((int)hashMap.get(y) == 1) {
return y;
}
}
return 0;
}
时间复杂度:O(n)
空间复杂度:O(n^2)
HashMap是通过所记录的Value值来确定是否重复的!!
2、暴力解法
class Solution {
public int singleNumber(int[] nums) {
for(int i=0; i<nums.length;i++) {
for(int j=0; j<nums.length; j++) {
if(nums[j] == nums[i] && j!=i) {
break;
}else if(j==nums.length-1) {
return nums[i];
}
}
}
return 0;
}
}
时间复杂度:O(n^2)
空间复杂度:O(n)
3、异或:相同为0,不同为1
class Solution {
public int singleNumber(int[] nums) {
int k = nums[0];
for(int i=1; i<nums.length; i++) {
k = k ^ nums[i];
}
return k;
}
}
时间复杂度:O(n)
空间复杂度:O(n)