zoukankan      html  css  js  c++  java
  • 4.Single Number && Single Number (II)

    Single Number:

    1. Given an array of integers, every element appears twice except for one. Find that single one.

    Note:
    Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

    代码:

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int result = 0;
            for(int i = 0; i < n; ++i){
                result ^= A[i];
            }
            return result;
        }
    };
    

    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?

     方法1:(分别计算各位1的个数 mod 3)

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int count[32] = {0};
            int result = 0;
            int bit = sizeof(int) * 8;
            for(int i = 0; i < n; ++i) {
                for(int j = 0; j < bit; ++j){
                    if((A[i] >> j) & 0x1) count[j] = (count[j] + 1) % 3;
                }
            }
            for(int i = 0; i < bit; ++i){
                result |= (count[i] << i); 
            }
            return result;
        }
    };
    

     方法2:(三个变量,分别记录出现一次,出现两次,出现三次的值)

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int one, two, three;
            one = two = 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;
        }
    };
    
  • 相关阅读:
    Java中获取键盘输入值的三种方法
    java多线程处理与数据集合
    Apachetomcat学习
    Java之枚举
    多例设计模式与枚举
    权限管理(数据库部分)
    hdu 2458(最大独立集)
    hdu 1507(最大匹配)
    hdu 1350+hdu 1960(最小路径覆盖)
    hdu 1845(最大匹配)
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3622257.html
Copyright © 2011-2022 走看看