码迷,mamicode.com
首页 > 其他好文 > 详细

137. Single Number II - Medium

时间:2019-01-10 15:30:40      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:put   tco   pre   problems   变化   length   ever   run   note   

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

标签:put   tco   pre   problems   变化   length   ever   run   note   

原文地址:https://www.cnblogs.com/fatttcat/p/10249861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!