【leetcode刷题笔记】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?


 

题解:线性时间,O(1)的空间复杂度,只能把整数写成二进制的形式运算了。具体做法如下:

比如有一个数组{5,5,5,3,2,3,3},这些数写成二进制如下:

5:101

5:101

5:101

3:011

2:010

3:011

3:011

我们分别统计这三位的1的个数,然后对3取模,得到每一位的结果结合起来就是010,就是只出现一次的数字2.

所以,我们可以设置一个32位的数组,然后对A中的所有数字,统计这32位中每一位上1的个数,然后对3取模,最后得到的32位的二进制数就是只出现一次的那个数了。

Java代码如下:

复制代码
 1 public class Solution {
 2     public int singleNumber(int[] A) {
 3         int[] digits = new int[32];
 4         for(int i = 0;i < 32;i++){
 5             for(int j = 0;j < A.length;j++){
 6                 digits[i] += (A[j] >> i)&1;
 7             }
 8         }
 9         int result = 0;
10         for(int i = 0;i < 32;i++){
11             result += (digits[i]%3) << i;
12         }
13         return result;
14     }
15 }
复制代码

 

posted @   SunshineAtNoon  阅读(133)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2014-03-31 【leetnode刷题笔记】Maximum Depth of binary tree
2014-03-31 【leetcode刷题笔记】Single Number
点击右上角即可分享
微信分享提示