LeetCode 2.1.24 Single Number II

来源:互联网 发布:设计模式 java 编辑:程序博客网 时间:2024/06/14 00:08

2.1.24 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 usingextra memory?

2.1数组37分析

本题考察的是位运算。

方法1:创建一个长度为sizeof(int)的数组count[sizeof(int)],count[i]表示所有元素的1i位出现的次数。如果count[i]3的整数倍,则忽略;否则就把该位取出来组成答案。

方法2:用ones记录到当前处理的元素为止,二进制1出现“1次”(mod 3之后的1)的有哪些二进制位;用twos记录到当前计算的变量为止,二进制1出现“2次”(mod 3之后的2)的有哪些二进制位。当onestwos中的某一位同时为1时表示该二进制位上1出现了3次,此时需要清零。即用二进制模拟三进制运算。最终ones记录的是最终结果。

代码1

// LeetCode, Single Number II// 方法1,时间复杂度O(n),空间复杂度O(1)class Solution {public:

int singleNumber(int A[], int n) {const int W = sizeof(int) * 8; // 整数字长int count[W]; //每个位上1出现的次数fill_n(&count[0], W, 0);for (int i = 0; i < n; i++) {

              for (int j = 0; j < W; j++) {                  count[j] += (A[i] >> j) & 1;                  count[j] %= 3;

}}

          int result = 0;          for (int i = 0; i < W; i++) {
              result += (count[i] << i);          }
          return result;      }

};


代码2

// LeetCode, Single Number II// 方法2,时间复杂度O(n),空间复杂度O(1)class Solution {public:

      int singleNumber(int A[], int n) {          int ones = 0, twos = 0, threes = 0;          for (int i = 0; i < n; ++i) {
              twos |= (ones & A[i]);              ones ^= A[i];              threes = ~(ones & twos);              ones &= threes;
              twos &= threes;          }
page43image15784
page44image1240
    return ones;}

}; 



// LeetCode, Single Number II
// 
方法1,时间复杂度O(n),空间复杂度O(1)class Solution {
public:

int singleNumber(int A[], int n) {
const int W = sizeof(int) * 8; // 
整数字长int count[W]; //每个位上1出现的次数fill_n(&count[0], W, 0);
for (int i = 0; i < n; i++) {

              for (int j = 0; j < W; j++) {                  count[j] += (A[i] >> j) & 1;                  count[j] %= 3;

}}

          int result = 0;          for (int i = 0; i < W; i++) {
              result += (count[i] << i);          }
          return result;      }

};

0 0