zoukankan      html  css  js  c++  java
  • 137. Single Number II

    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;
        }
    }
  • 相关阅读:
    openstack--9--深入理解虚拟机
    KVM部署、使用、调优
    Mysql主从---删除master.info和relya-log.info实验
    saltstack实战4--综合练习3
    saltstack实战4--综合练习4
    saltstack实战4--综合练习2
    nmap命令-----高级用法
    saltstack实战4--综合练习1
    saltstack实战3--配置管理之pillar
    nmap命令-----基础用法
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10249861.html
Copyright © 2011-2022 走看看