当前位置:网站首页>【剑指 Offer】56 - I. 数组中数字出现的次数
【剑指 Offer】56 - I. 数组中数字出现的次数
2022-07-02 21:32:00 【LuZhouShiLi】
剑指 Offer 56 - I. 数组中数字出现的次数
题目
一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
思路
对数组nums进行一遍抑或运算,得到两个只出现一次数字的抑或运算结果,初始化一个数字m = 1,x和y是不同的,所以一定有一位是1,那么只要找到为1的二进制位,就可以将nums拆分成两个子数组,初始化一个辅助变量 m=1 ,通过与运算从右向左循环判断,可获取整数 x⊕y 哪一位是1。然后拆分nums为两个子数组,分别遍历两个子数组执行抑或,就可以得到两个只出现一次的数字。
代码
class Solution {
public:
vector<int> singleNumbers(vector<int>& nums) {
int x = 0, y = 0, n = 0, m = 1;
for(int num : nums)
n ^= num;
while((n & m) == 0)
m <<= 1;
for(int num : nums) {
if(num & m) x ^= num;
else y ^= num;
}
return vector<int> {
x, y};
}
};
边栏推荐
- Golang string segmentation
- Redis分布式锁故障,我忍不住想爆粗...
- Structure array, pointer and function and application cases
- China plastic bottle and container market trend report, technological innovation and market forecast
- Share the easy-to-use fastadmin open source system - Installation
- 基本IO接口技术——微机第七章笔记
- How does esrally perform simple custom performance tests?
- Hot backup routing protocol (HSRP)
- It is said that this year gold three silver four has become gold one silver two..
- Add two numbers of leetcode
猜你喜欢
[question brushing diary] classic questions of dynamic planning
[shutter] shutter layout component (physicalmodel component)
I drew a Gu ailing with characters!
Welfare, let me introduce you to someone
Today, I met a Alipay and took out 35K. It's really sandpaper to wipe my ass. it's a show for me
关于测试用例
How to test the process of restoring backup files?
[shutter] statefulwidget component (create statefulwidget component | materialapp component | scaffold component)
Volvo's first MPV is exposed! Comfortable and safe, equipped with 2.0T plug-in mixing system, it is worth first-class
D4: unpaired image defogging, self enhancement method based on density and depth decomposition (CVPR 2022)
随机推荐
MySQL learning record (1)
Golang string segmentation
Research Report on market supply and demand and strategy of China's right-hand outward rotation entry door industry
Basic knowledge of tree and binary tree (detailed illustration)
China plastic bottle market trend report, technological innovation and market forecast
Check the confession items of 6 yyds
How to test the process of restoring backup files?
Unexpectedly, there are such sand sculpture code comments! I laughed
Structure array, pointer and function and application cases
Detailed explanation of OSI seven layer model
Centos7 installation and configuration of redis database
[dynamic planning] p1220: interval DP: turn off the street lights
ctf-HCTF-Final-Misc200
kernel_ uaf
How is LinkedList added?
Research Report on market supply and demand and strategy of China's plastic pump industry
MySQL learning record (5)
MySQL learning record (4)
China's log saw blade market trend report, technological innovation and market forecast
Go language learning summary (5) -- Summary of go learning notes