LeetCode----Single NumberII

95 篇文章 0 订阅
93 篇文章 0 订阅

Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

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


分析:

数组中其他元素均出现3次,只有一个元素只出现过一次,找出那个single元素。

此题有两种解法。


解法一:

对于两个元素,我们使用异或操作即让它清零,即不影响后面的操作,有A^B^A = B. 而当元素为三个时,如何让A*B*A*A = B呢(注意*表示为一种运算,能够满足该表达式)?

我们使用跟3取余的方式来处理。

这种方式适合这类题目的解法,比如所有元素出现m次,一个元素出现1次,可以与m取余。


代码:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int res = 0;
        int k = 0;
        while(k < 32){
           int temp = 0;
           for(int i=0; i<nums.size(); i++){
               temp += ((nums[i] >> k) & 1 );
           }  
           if(temp%3 != 0){
               res = res | (1<<k);
           }   
           k++;
        }
        return res;
    }
};


解法二:

利用二进制模拟三进制,比如用a,b描述1的状态,

当A出现了一次,a,b的状态为:

0,0 -> 1, 0

出现了两次,a,b的状态为:

1, 0 -> 0, 1

出现了三次,a,b的状态为:

0, 1 -> 1, 1

而当a,b的状态为1,1时,即可以知道当前A已经出现过三次了,将它们清零:

1,1 -> 0,0


代码:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int ones = 0, twos = 0, threes = 0;
        for(int i = 0 ; i < nums.size() ; i++){
            twos |= (ones & nums[i]);
            ones ^= nums[i];
            threes = ~(ones & twos);
            ones &= threes;
            twos &= threes;
        }
        return ones;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值