LeetCode 137. Single Number II--三次异或消除相同的数--C++,Python解法

100 篇文章 3 订阅
44 篇文章 2 订阅

题目地址:Single Number II - LeetCode


Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,3,2]
Output: 3

Example 2:

Input: [0,1,0,1,0,1,99]
Output: 99

这是一道谷歌的面试题
这道题目意思很简单,就是找出没出现3次的数字。
最容易想到的想法是用字典,count。
Python解法如下:

from collections import Counter
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        s=Counter(nums)
        for i in s:
            if s[i]!=3:
                return i

然后会想可不可以用位运算,毕竟使用字典还是很费时的。
如何使用三次异或消去出现3次的数字。
官方解法如下:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        seen_once = seen_twice = 0
        
        for num in nums:
            # first appearance: 
            # add num to seen_once 
            # don't add to seen_twice because of presence in seen_once
            
            # second appearance: 
            # remove num from seen_once 
            # add num to seen_twice
            
            # third appearance: 
            # don't add to seen_once because of presence in seen_twice
            # remove num from seen_twice
            seen_once = ~seen_twice & (seen_once ^ num)
            seen_twice = ~seen_once & (seen_twice ^ num)

        return seen_once

异或的解法难度极大,建议去看leetcode的讨论区:


C++解法如下:

class Solution {
public:
   int singleNumber(vector<int>& nums) {
        int one = 0, two = 0, three = 0;
        for (int i = 0; i < nums.size(); ++i) {
            two |= one & nums[i];
            one ^= nums[i];
            three = one & two;
            one = one ^ three;
            two = two ^ three;
        }
        return one;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值