• 剑指offer | 数组中只出现一次的数字 | 24



    思路分析

    最简单就是使用一个哈希表来计数,然后找出次数为1的两个.

    还有就是异或!
    异或的性质: 两个相同的数,异或的结果为0. 0异或任何数都等于自身.
    那么如果数组中只有一个数出现了一次,其他都出现了两次,那么对整个数组异或,最后的答案就是只出现一次的那个数.

    暴力

    使用哈希表计数

    cpp

    class Solution {
    public:
        vector<int> findNumsAppearOnce(vector<int>& nums) {
            unordered_map<int,int> d;
            for(auto x:nums)
                if(d.count(x)==0)d[x]=1;
                else d[x]++;
            vector<int> res;
            for(auto i=d.begin();i!=d.end();i++)
                if(i->second==1)res.push_back(i->first);
            return res;
        }
    };
    

    python

    # -*- coding:utf-8 -*-
    class Solution:
        # 返回[a,b] 其中ab是出现一次的两个数字
        def FindNumsAppearOnce(self, array):
            # write code here
            d = dict()
            for x in array:
                if x not in d:d[x]=1
                else: d[x]+=1
            res = []
            for k,v in d.items():
                if v==1:res.append(k)
            
            return res
    

    异或

    然后将第i位为1的分为一组,将第i位为0的分为一组.
    这样每一组都只存在一个出现一次的数.

    cpp

    class Solution {
    public:
        vector<int> findNumsAppearOnce(vector<int>& nums) {
            int sum = 0;
            for(auto x:nums)sum^=x;// sum=x^y
            int k=0;
            while(!(sum>>k&1))k++;// 找到第一个1的位置
            int first=0;
            for(auto x:nums)
                if(x>>k&1)first^=x;
            return vector<int>{first,sum^first};
            
        }
    };
    

    python

    class Solution(object):
        def findNumsAppearOnce(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            sum = 0
            for x in nums:
                sum ^= x
            k = 0
            while not sum>>k&1:k+=1
            first = 0
            for x in nums:
                if x>>k&1:first^=x
            return [first,sum^first]
    
  • 相关阅读:
    Best HTTP
    Unity3D游戏轻量级xlua热修复框架
    线段树
    7.1
    BZOJ 3011: [Usaco2012 Dec]Running Away From the Barn( dfs序 + 主席树 )
    BZOJ 3585: mex( 离线 + 线段树 )
    2015暑假集训
    BZOJ 3398: [Usaco2009 Feb]Bullcow 牡牛和牝牛( dp )
    BZOJ 2693: jzptab( 莫比乌斯反演 )
    2015.7.31
  • 原文地址:https://www.cnblogs.com/Rowry/p/14316917.html
Copyright © 2020-2023  润新知