LeetCode 2.1.24 Single Number II

本文介绍了使用位运算解决数组中出现次数为三次的唯一元素问题的方法,包括两种实现方式:一种是通过创建长度为sizeof(int)的数组来记录每个位上1出现的次数,另一种则是通过二进制模拟三进制运算的方式。两种方法的时间复杂度均为O(n),空间复杂度均为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
      }

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值