当前位置:网站首页>leetcode 268. 丢失的数字(异或!!)
leetcode 268. 丢失的数字(异或!!)
2022-08-03 20:06:00 【会编程的露娜】
给定一个包含 [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到n的所有值都异或一遍,这样算是将所有的值都记录一遍,再对数组中的每一个值异或,因为同一个数异或2次对原值没有影响,即 a ^ b ^ b =a 。
那么到最后就只剩下没有出现的那个数字了。
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,记录所有数都出现时的总和 sum,再将数组中的每个值都相加 he,他们的差值(sum-he)即为没有出现的数字。
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;
}
};
思路三:排序
对数组进行排序,如果对应位置的序号和数值不相等,那么序号就是缺失的数字。
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; //如果是最后一个数缺失,那么循环结束条件时i==n,最后返回的也是n
}
};
边栏推荐
- 【飞控开发高级教程4】疯壳·开源编队无人机-360 度翻滚
- (十六)51单片机——红外遥控
- Detailed demonstration pytorch framework implementations old photo repair (GPU)
- 虚拟机vmware设置桥接模式上网
- 622 设计循环队列——Leetcode天天刷【循环队列,数组模拟,双指针】(2022.8.2)
- xss.haozi练习通关详解
- 利用net-snmp的库实现snmpget,snmpset
- PHP according to the longitude and latitude calculated distance two points
- Anaconda virtual environment migration
- ARMuseum
猜你喜欢
Network protocol-TCP, UDP difference and TCP three-way handshake, four wave
JS 内置构造函数 扩展 prototype 继承 借用构造函数 组合式 原型式creat 寄生式 寄生组合式 call apply instanceof
Statistical machine learning 】 【 linear regression model
149. The largest number on a straight line, and check the set
倒计时2天,“文化数字化战略新型基础设施暨文化艺术链生态建设发布会”启幕在即
149. 直线上最多的点数-并查集做法
虚拟机vmware设置nat模式上网
百利药业IPO过会:扣非后年亏1.5亿 奥博资本是股东
后台图库上传功能
高性能计算软件与开源生态| ChinaOSC
随机推荐
RNA-ATTO 390|RNA-ATTO 425|RNA-ATTO 465|RNA-ATTO 488|RNA-ATTO 495|RNA-ATTO 520近红外荧光染料标记核糖核酸RNA
Line the last time the JVM FullGC make didn't sleep all night, collapse
虚拟机vmware设置nat模式上网
LeetCode 622. 设计循环队列
2022 年值得尝试的 7 个 MQTT 客户端工具
从腾讯阿里等大厂出来创业搞 Web3、元宇宙的人在搞什么
(十六)51单片机——红外遥控
力扣203-移除链表元素——链表
Go语言类型与接口的关系
Internet Download Manager简介及下载安装包,IDM序列号注册问题解决方法
告诉你0基础怎么学好游戏建模?
刷题错题录1-隐式转换与精度丢失
matplotlib画polygon, circle
多模态 参考资料汇总
汉源高科8光口12电口交换机千兆8光8电12电16电网管型工业以太网交换机
友宏医疗与Actxa签署Pre-M Diabetes TM 战略合作协议
第三方验收测试报告有什么作用?如何获取权威软件测试报告?
The sword refers to Offer II 044. The maximum value of each level of the binary tree-dfs method
小马智行起诉擎天智卡:索赔6000万 彭军称要斗争到底
Benchmarking Lane-changing Decision-making for Deep Reinforcement Learning