只出现一次的数字
c++解法
第一种解题思路是:使用map来实现,线性时间复杂度,但是使用了额外空间。
class Solution {
public:
int singleNumber(vector<int>& nums) {
//使用map来做
map<int,int> mmap;
for(auto i:nums){
if(mmap.count(i)==0) mmap[i]=1;
else mmap[i]+=1;
}
for(auto j:mmap){
if(j.second==1) return j.first;
}
return 0;
}
};
第二种解题思路是使用异或来解决,异或是相同的二进制位取0,不同的则取1,用在这道题目中,正好将出现两次的数全部变为0,剩下的就是只出现一次的那个数。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans=0;
for(auto i:nums) ans^=i;
return ans;
}
};
java解法
使用HashMap,注意要用封装类型
class Solution {
public int singleNumber(int[] nums) {
HashMap<Integer,Integer> mmap=new HashMap<Integer,Integer>();
for(int i:nums){
int v=mmap.getOrDefault(i,0);//当键不存在时返回默认值
mmap.put(i,++v);
}
//遍历
for(int key:mmap.keySet()){
if(mmap.get(key)==1) return key;
}
return 0;
}
}
使用异或解法
class Solution {
public int singleNumber(int[] nums) {
int ans=0;
for(int i:nums) ans^=i;
return ans;
}
}
python解法
使用字典解法
class Solution:
def singleNumber(self, nums: List[int]) -> int:
mmap={}
for i in nums:
mmap[i]=mmap.get(i,0)+1#键不存在时返回默认值
#遍历字典
for key in mmap.keys():
if mmap[key]==1:
return key
return 0
异或解法
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ans=0
for i in nums:
ans^=i
return ans