劍指Offer(Python多種思路實現):數組中數字出現的次數

劍指Offer(Python多種思路實現):數組中數字出現的次數

面試56題:

題目:數組中數字出現的次數

題:一個整型數組裏除了兩個數字之外,其他的數字都出現了兩次。請寫程序找出這兩個只出現一次的數字。

解題思路一:

class Solution:
    # 返回[a,b] 其中ab是出現一次的兩個數字
    def FindNumsAppearOnce(self, array):
        # write code here
        if len(array)<2:
            return
        resultEOR=0
        for i in array:
            resultEOR =resultEOR^ i

        index=self.FindFirstBit(resultEOR)

        res1,res2=0,0
        for j in array:
            if self.IsBit(j,index):
                res1^=j
            else:
                res2^=j
        return [res1, res2]
            
    
    def FindFirstBit(self,num):
        '''
        用於在整數num的二進制表示中找到最右邊是1的位
        '''
        indexBit=0
        while(num&1==0 and indexBit<32):
            num=num>>1
            indexBit+=1
        return indexBit


    def IsBit(self,num,indexBit):
        '''
        用於判斷在num的二進制表示中從右邊起的indexBit位是否爲1
        '''
        num = num >> indexBit
        return (num&1)

解題思路二:

class Solution:
    # 返回[a,b] 其中ab是出現一次的兩個數字
    def FindNumsAppearOnce(self, array):
        # write code here
        from collections import Counter

        res=Counter(array).most_common()[-2:]
        return list(map(lambda x:x[0],res))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章