当前位置:网站首页>剑指 Offer 56 - I. 数组中数字出现的次数
剑指 Offer 56 - I. 数组中数字出现的次数
2022-08-09 03:15:00 【田园诗人之园】
一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
示例 1:
输入:nums = [4,1,4,6]
输出:[1,6] 或 [6,1]
示例 2:
输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10] 或 [10,2]
限制:
2 <= nums.length <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
首先将数组排序,然后依次从前往后遍历,如果前后两个元素相等,则向后偏移两个位置,否则记录当前元素,向后偏移一个位置。该方法由于使用sort()的缘故,会使得算法的时间复杂度变为O(NlogN)
class Solution {
public:
vector<int> singleNumbers(vector<int>& nums) {
vector<int> res;
int n = nums.size();
int i = 0;
sort(nums.begin(), nums.end());
for (i = 0; i < n - 1;) {
if (nums[i] == nums[i + 1]) {
i += 2;
continue;
}
res.push_back(nums[i]);
i++;
}
if (i == n - 1) {
res.push_back(nums[i]);
}
return res;
}
};
采用官网上给出的方法:
class Solution {
public:
vector<int> singleNumbers(vector<int>& nums) {
vector<int> res;
int ans = 0;
int a = 0, b = 0;
for (auto &i: nums) {
ans ^= i;
}
int div = 1;
while ((div & ans) == 0) {
div <<= 1;
}
for (auto &i: nums) {
if (div & i) {
a ^= i;
}
else {
b ^= i;
}
}
res.push_back(a);
res.push_back(b);
return res;
}
};
边栏推荐
猜你喜欢
随机推荐
C专家编程 第10章 再论指针 10.2 指针数组就是Iliffle向量
Mysql表打不开
2022-08-08 第五小组 顾祥全 学习笔记 day31-集合-Junit单元测试
uniapp uview uselect 时间选择 日期生成代码
C专家编程 第9章 再论数组 9.1 什么时候数组与指针相同
What are the functions and applications of the smart counter control board?
C专家编程 第9章 再论数组 9.2 为什么会发生混淆
jsx定义与规则
Embedded system driver advanced [2] - platform bus driver development _ basic framework
C专家编程 第9章 再论数组 9.6 C语言的多维数组
SQL注入(1)
以赛促练-力扣第84场双周赛反思以及第305场周赛补题
手把手教你uniapp接入聊天IM即时通讯功能-源码分享
Promoting practice with competitions-Like the 84th biweekly game reflection and the 305th weekly game supplementary questions
Kubernetes:(十四)安全机制(一定要做好安全措施哦)
【面试整理】-- 多线程
Win7电脑无法进入睡眠模式?
卷积神经网络的推导过程
光刻机随感
01| 数据类型