当前位置:网站首页>leetcode 268. Missing Numbers (XOR!!)
leetcode 268. Missing Numbers (XOR!!)
2022-08-03 20:13:00 【Luna programming】
给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数.
示例 1:
输入:nums = [3,0,1]
输出:2
解释:n = 3,(n为数组中元素个数)因为有 3 个数字,所以所有的数字都在范围 [0,3] 内.2 是丢失的数字,因为它没有出现在 nums 中.
示例 2:
输入:nums = [9,6,4,2,3,5,7,0,1]
输出:8
解释:n = 9,因为有 9 个数字,所以所有的数字都在范围 [0,9] 内.8 是丢失的数字,因为它没有出现在 nums 中.
提示:
n == nums.length
1 <= n <= 104
0 <= nums[i] <= n
nums 中的所有数字都 独一无二
进阶:你能否实现线性时间复杂度、仅使用额外常数空间的算法解决此问题?
思路一:异或
首先将从0到nAll values of are XORed once,This is to record all the values,Then XOR each value in the array,Because the same number is XORed2times have no effect on the original value,即 a ^ b ^ b =a .
Then in the end, only the number that did not appear is left.
class Solution {
public:
int missingNumber(vector<int>& nums) {
int ans=0;
int n=nums.size();
for(int i=0;i<=n;++i)
ans^=i;
for(vector<int>::iterator it=nums.begin();it!=nums.end();++it)
ans^=(*it);
return ans;
}
};
思路二: 作差
先从0一直加到n,Record the sum when all numbers are present sum,Then add each value in the array he,他们的差值(sum-he)That is, the number that does not appear.
class Solution {
public:
int missingNumber(vector<int>& nums) {
int sum=0,he=0;
sort(nums.begin(),nums.end());
int n=nums.size();
for(int i=0;i<=n;++i)
sum+=i;
for(vector<int>::iterator it=nums.begin();it!=nums.end();++it)
he+=(*it);
return sum-he;
}
};
思路三:排序
对数组进行排序,If the serial number and value of the corresponding position are not equal,Then the ordinal is the missing number.
class Solution {
public:
int missingNumber(vector<int>& nums) {
sort(nums.begin(),nums.end());
int n=nums.size(),i=0;
for( ;i<n;++i){
if(i!=nums[i])
break;
}
return i; //If the last number is missing,Then the loop end conditioni==n,最后返回的也是n
}
};
边栏推荐
- CSDN帐号管理规范
- leetcode 剑指 Offer 58 - II. 左旋转字符串
- Pytorch GPU 训练环境搭建
- 调用EasyCVR云台控制接口时,因网络延迟导致云台操作异常该如何解决?
- leetcode 16.01. 交换数字(不使用临时变量交换2个数的值)
- 调用EasyCVR接口时视频流请求出现404,并报错SSL Error,是什么原因?
- 从腾讯阿里等大厂出来创业搞 Web3、元宇宙的人在搞什么
- 149. 直线上最多的点数-并查集做法
- 5 款漏洞扫描工具:实用、强力、全面(含开源)
- RNA核糖核酸修饰荧光染料|HiLyte Fluor 488/555/594/647/680/750标记RNA核糖核酸
猜你喜欢
随机推荐
微导纳米IPO过会:年营收4.28亿 君联与高瓴是股东
leetcode 072. Finding Square Roots
Kubernetes资源编排系列之三: Kustomize篇 作者 艄公(杨京华) 雪尧(郭耀星)
极验深知v2分析
力扣206-反转链表——链表
多模态 参考资料汇总
李沐动手学深度学习V2-BERT微调和代码实现
EMQX Newsletter 2022-07|EMQX 5.0 正式发布、EMQX Cloud 新增 2 个数据库集成
ES6-箭头函数
leetcode 2119. Numbers reversed twice
Go语言类型与接口的关系
【leetcode】剑指 Offer II 008. 和大于等于 target 的最短子数组(滑动窗口,双指针)
嵌入式分享合集27
149. The largest number on a straight line, and check the set
面试官:为什么 0.1 + 0.2 == 0.300000004?
EasyCVR平台海康摄像头语音对讲功能配置的3个注意事项
云服务器如何安全使用本地的AD/LDAP?
MapReduce介绍及执行过程
tRNA甲基化偶联3-甲基胞嘧啶(m3C)|tRNA-m3C (3-methylcy- tidine)
List类的超详细解析!(超2w+字)









