只出现一次的数字

只出现一次的数字

题目链接

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值