zoukankan      html  css  js  c++  java
  • LeetCode -- Single Number II

    Question:

    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?

    Analysis:

    给出一个整数数组,除了一个数字只出现一次外,其他的数字均出现3次,找到那个只出现一次的特殊数字。

    注意:你的算法应该在线性时间复杂度内完成。可以不用额外的空间完成任务吗?

    这种 N + 1 找1 模式的题目,应该很容易想到用位运算求解。由于在这个问题中,N = 3是奇数,因此我们不能简单的使用异或运算解决。想象一下,将数组中每个数字都转化为二进制的表示形式。那么在32位数组中,将所有数字按位相加,一共会有三种情况:

    a. 结果为所有出现3次的数字的对应位相加之和,为 3 * n;

    b. 结果为所有出现3次的数字的对应位与特殊数字的对应位相加之和,为 3 * n + 1;

    c. 结果为只有特殊数字的对应位,为 1.

    因此,我们只需将数组中的所有数字按位相加然后按3去模即可得到只出现一次的特殊数字。

    Answer:

    public class Solution {
        public int singleNumber(int[] A) {
            int result = 0;
            int[] a = new int[32];
            for(int i=0; i<A.length; i++) {
                for(int j=0; j<a.length; j++) {
                    if((A[i] & (1 << j)) != 0) 
                        a[j] = (a[j] + 1) % 3;
                }
            }
            for(int i=0; i<32; i++) {
                if(a[i] > 0)
                    result |= (a[i] << i);
            }
            return result;
        }
    }
  • 相关阅读:
    django-based blog- mezzanine
    echo "hello" | nc -4t -w1 localhost 8001
    boost静态链接的问题 -lgcc_s
    Vim 新用法
    解决docker中DNS查询的问题
    centos 升级GCC/G++
    enable c++11 in autoconf in fucking gnu auto tools
    Fucking "pkg-config not found"
    在CentOS 6.X 上面安装 Python 2.7.X
    redis sentinel 配置
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5200247.html
Copyright © 2011-2022 走看看