[Leetcode] 137。一度だけ現れるナンバーII

[Leetcode] 137。一度だけ現れるナンバーII

トピック

ここに画像の説明を挿入します

python3言語

コード1:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        list1=nums.copy()
        for i in nums:
            list1.remove(i)
            if i not in list1:
                return i
            list1.append(i)

コード1、次のように実行します。
ここに画像の説明を挿入します
コード2:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:      
        return (3 * sum(set(nums)) - sum(nums)) // 2

次のように実行されるコード2:
ここに画像の説明を挿入します

C ++言語

class Solution {
    
    
public:
    int singleNumber(vector<int>& nums) {
    
    
        int ones = 0, twos = 0;
        for (int x: nums) {
    
    
            // 之前出现过两次的,这次再出现就是出现了三次
            int threes = twos & x;

            // 之前出现过两次,这次没出现,是出现了两次。
            // 之前出现过一次的,这次再出现,也是出现了两次。
            twos = (twos & ~x) | (ones & x);

            // 统计记录出现了奇数次的,并从其中清除出现三次的。
            // 这样ones里面始终只会记录出现了一次的。
            ones = ones ^ x;
            ones &= ~threes;
        }
        return ones;

    }
};

次のように実行します。
ここに画像の説明を挿入します

おすすめ

転載: blog.csdn.net/jn10010537/article/details/114550571