当前位置:网站首页>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
}
};
边栏推荐
猜你喜欢
随机推荐
5 款漏洞扫描工具:实用、强力、全面(含开源)
EMQX Newsletter 2022-07|EMQX 5.0 正式发布、EMQX Cloud 新增 2 个数据库集成
云服务器如何安全使用本地的AD/LDAP?
利用 rpush 和 blpop 实现 Redis 消息队列
Statistical machine learning 】 【 linear regression model
软件测试基本流程有哪些?权威的第三方软件检测机构推荐
力扣707-设计链表——链表
622 设计循环队列——Leetcode天天刷【循环队列,数组模拟,双指针】(2022.8.2)
RNA核糖核酸修饰荧光染料|HiLyte Fluor 488/555/594/647/680/750标记RNA核糖核酸
Anaconda virtual environment migration
List类的超详细解析!(超2w+字)
危化企业双重预防机制数字化建设进入全面实施阶段
tRNA-m5C转运RNA(tRNA)修饰5-甲基胞嘧啶(m5C)|tRNA修饰m1Am2A (2-methyladenosine)
149. 直线上最多的点数-并查集做法
第三方验收测试报告有什么作用?如何获取权威软件测试报告?
Golang死信队列的使用
亚马逊云科技 Build On 2022 - AIot 第二季物联网专场实验心得
leetcode 461. 汉明距离
MySQL Basics
glide set gif start stop