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

    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?

    创建一个长度为32的数组a,a[i]表示所有数字在i位出现的次数。
    假如a[i]是3的整数倍,则忽略;否则就把该位取出来组成答案。
    空间复杂度O(1).

    int sol1(int A[], int n)
    {
        int count[32];
        int result = 0;
        for (int i = 0;i < 32;++i) {
            count[i] = 0;
            for (int j = 0;j < n;++j) {
                if ((A[j] >> i) & 1) count[i] = (count[i] + 1) % 3;
            }
            result |= (count[i] << i);
        }
        return result;
    }

    另一个方法,同样的原理,用3个整数来表示INT的各位的出现次数情况,one表示出现
    了1次,two表示出现了2次。当出现3次的时候该位清零。最后答案就是one的值。

    int sol2(int A[], int n)
    {
        int one = 0, two = 0, three = 0;
        for (int i = 0;i < n;++i) {
            two |= one & A[i];
            one ^= A[i];
            three = one & two;
            one &= ~three;
            two &= ~three;
        }
        return one;
    }

     1 public class Solution {
     2     public int singleNumber(int[] A) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         int count[] = new int[32];
     5         int result = 0;
     6         for (int i = 0; i < 32; i ++){
     7             for (int j = 0; j < A.length; j ++) {
     8                 if (((A[j] >> i) & 1) == 1) 
     9                     count[i] = (count[i] + 1) % 3;
    10             }
    11             result |= (count[i] << i);
    12         }
    13         return result;
    14     }
    15 }
  • 相关阅读:
    sort()的部分用法
    蓝桥杯 算法训练 审美课
    蓝桥杯 基础练习 查找整数
    2018年第九届蓝桥杯【C++省赛B组】【第二题:明码】
    蓝桥杯 特殊回文数
    比较两文本程序
    蓝桥杯 基础练习 十六进制转八进制
    Python | 用Pyinstaller打包发布exe应用
    SpringBoot-04-整合JDBC
    SpringBoot-03-自定义Starter
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3362972.html
Copyright © 2011-2022 走看看