1. 程式人生 > >137. Single Number II - Medium

137. Single Number II - Medium

exactly leet class discuss have acc element code pro

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

reference: https://leetcode.com/problems/single-number-ii/discuss/43302/Accepted-code-with-proper-Explaination.-Does-anyone-have-a-better-idea

對於每一個元素,統計其出現次數,若出現次數達到3,則置為0,最後所有元素的次數都為0,除了只出現一次的元素是1

即0->1->2->0,如果用二進制表示:00->01->10->00。換一種方便的表示方法:00->10->01->00,這樣可以用兩個參數ones twos來表示,最後返回ones就是只出現一次的數字

ones和twos的變化過程:

0    0   (初始)

0->1  0->0

1->0  0->1

0->0  1->0

遍歷整個數組,對每一個元素,先存入ones,再清空ones存入twos,再清空twos

time: O(n), space: O(1)

class Solution {
    public int singleNumber(int[] nums) {
        int ones = 0, twos = 0;
        for(int k : nums) {
            ones = (ones ^ k) & ~twos;
            twos 
= (twos ^ k) & ~ones; } return ones; } }

另一種理解方法:模擬三進制

class Solution {
    public int singleNumber(int[] nums) {
        int one = 0, two = 0, three = 0;
        for(int i = 0; i < nums.length; i++) {
            two |= one & nums[i];
            one ^= nums[i];
            three = one & two;
            one &= ~three;
            two &= ~three;
        }
        return one;
    }
}

137. Single Number II - Medium