[137]Single Number II

【题目描述】

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

【思路】

其实和Single Number的思路差不多,第一种方法是将数组排序,遍历数组,判断查找哪个数字没有出现满3次,第二种方法则是利用位操作。

【代码】

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int cnt=1;
        sort(nums.begin(),nums.end());
        for(int i=1;i<nums.size();i++){
            if(nums[i]==nums[i-1]){
                cnt++;
                continue;
            }
            if(cnt!=3) return nums[i-1];
            else cnt=1;
        }
        return nums[nums.size()-1];
    }
};

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int a,b,c;
        a=b=0;
        for(int i=0;i<nums.size();i++){
            c=nums[i];
            int tmp=(a&~b&~c)|(~a&b&c);
            b=(~a&b&~c)|(~a&~b&c);
            a=tmp;
        }
        return a|b;
    }
};

附该类问题解法:

this kind of question the key idea is design a counter that record state. the problem can be every one occurs K times except one occurs M times. for this question, K =3 ,M = 1(or 2) . so to represent 3 state, we need two bit. let say it is a and b, and c is the incoming bit. then we can design a table to implement the state move.

current   incoming  next
a b            c    a b
0 0            0    0 0
0 1            0    0 1
1 0            0    1 0
0 0            1    0 1
0 1            1    1 0
1 0            1    0 0

like circuit design, we can find out what the next state will be with the incoming bit.( we only need find the ones) then we have for a to be 1, we have

    current   incoming  next
    a b            c    a b
    1 0            0    1 0
    0 1            1    1 0

and this is can be represented by

a=a&~b&~c + ~a&b&c

and b can do the same we , and we find that

b= ~a&b&~c+~a&~b&c

and this is the final formula of a and b and just one of the result set, because for different state move table definition, we can generate different formulas, and this one is may not the most optimised. as you may see other's answer that have a much simple formula, and that formula also corresponding to specific state move table. (if you like ,you can reverse their formula to a state move table, just using the same way but reversely)

for this questions we need to find the except one as the question don't say if the one appears one time or two time , so for ab both

01 10 => 1
00 => 0

we should return a|b; this is the key idea , we can design any based counter and find the occurs any times except one . here is my code. with comment.

public class Solution {

    public int singleNumber(int[] nums) {
        //we need to implement a tree-time counter(base 3) that if a bit appears three time ,it will be zero.
        //#curent  income  ouput
        //# ab      c/c       ab/ab
        //# 00      1/0       01/00
        //# 01      1/0       10/01
        //# 10      1/0       00/10
        // a=~abc+a~b~c;
        // b=~a~bc+~ab~c;
        int a=0;
        int b=0;
        for(int c:nums){
            int ta=(~a&b&c)|(a&~b&~c);
            b=(~a&~b&c)|(~a&b&~c);
            a=ta;
        }
        //we need find the number that is 01,10 => 1, 00 => 0.
        return a|b;

    }
}

Many may wonder what 'a', 'b', 'c' means and how can we manipulate a number like one single bit, as you see in the code, a, b and c are all full 32-bit numbers, not bits. I cannot blame readers to have questions like that because the author did not make it very clear.

In Single Number, it is easy to think of XOR solution because XOR manipulation has such properties:

  1. Commutative: A^B == B^A, this means XOR applies to unsorted arrays just like sorted. (1^2^1^2==1^1^2^2)
  2. Circular: A^B^...^B == A where the count of B's is a multiple of 2.

So, if we apply XOR to a preceding zero and then an array of numbers, every number that appears twice will have no effect on the final result. Suppose there is a number H which appears just once, the final XOR result will be 0^H^...H where H appears as many as in input array.

When it comes to Single Number II (every one occurs K=3 times except one occurs M times, where M is not a multiple of K), we need a substitute of XOR (notated as @) which satisfies:

  1. Commutative: A@B == B@A.
  2. Circular: A@B@...@B == A where the count of B's is a multiple of K.

We need to MAKE the @ operation. This general solution suggests that we maintain a state for each bit, where the state corresponds to how many '1's have appeared on that bit, so we need a int[32] array.

bitCount = [];
for (i = 0; i < 32; i++) {
  bitCount[i] = 0;
}

The state transits like this:

for (j = 0; j < nums.length; j++) {
    n = nums[j];
    for (i = 0; i < 32; i++) {
        hasBit = (n & (1 << i)) != 0;
        if (hasBit) {
            bitCount[i] = (bitCount[i] + 1) % K;
        }
    }
}

I use '!=' instead of '>' in 'hasBit = (n & (1 << i)) != 0;' because 1<<31 is considered negative. After this, bitCount will store the module count of appearance of '1' by K in every bit. We can then find the wanted number by inspecting bitCount.

exept = 0;
for (i = 0; i < 32; i++) {
  if (bitCount[i] > 0) {
    exept |= (1 << i);
  }
}
return exept;

We use bitCount[i] > 0 as condition because there is no tell how many times that exceptional number appears.

Now let's talk about ziyihao's solution. His solution looks much magical than mine because given a fixed K, we can encode the state into a few bits. In my bitCount version, we have a int[32] array to store the count of each bit but a 32-bit integer is way more than what we need to store just 3 states. So ideally we can have a bit[32][2] structure to store the counts. We name bit[...][0] as 'a' and bit[...][1] as 'b' and the bits of n as 'c' and we have ziyihao's post.

The AC Javascript code:

var singleNumber = function(nums) {
    var k, bitCount, i, j, n, hasBit, exept;
    k = 3;
    bitCount = [];
    for (i = 0; i < 32; i++) {
        bitCount[i] = 0;
    }
    for (j = 0; j < nums.length; j++) {
        n = nums[j];
        for (i = 0; i < 32; i++) {
            hasBit = (n & (1 << i)) !== 0;
            if (hasBit) {
                bitCount[i] = (bitCount[i] + 1) % k;
            }
        }
    }
    exept = 0;
    for (i = 0; i < 32; i++) {
      if (bitCount[i] > 0) {
        exept |= (1 << i);
      }
    }
    return exept;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值