一、题目
给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。
示例 1:
输入:nums = [3,0,1]
输出:2
解释:n = 3,因为有 3 个数字,所以所有的数字都在范围 [0,3] 内。2 是丢失的数字,因为它没有出现在 nums 中。
示例 2:
输入:nums = [0,1]
输出:2
解释:n = 2,因为有 2 个数字,所以所有的数字都在范围 [0,2] 内。2 是丢失的数字,因为它没有出现在 nums 中。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/missing-number
二、思路
方法一:对数组进行排序,排好序后对数组进行遍历,中间遇到缺的值就是丢失的数字。
方法二:从0到n在数组中用find方法进行查找,没有找到的就是丢失的数字。
方法三:另设一个数组,每个元素初始化都为0,每遍历一个输入数组中的元素,就将新数组中对应位置的值设为1,遍历完输入数组后,新数组中元素为0对应的下标就是丢失的数字。
三、代码
方法一代码:(排序)
class Solution {
public:
int missingNumber(vector<int>& nums) {
int len = nums.size();
sort(nums.begin(), nums.end());
int index = 0;
for(int i=0; i<len; i++){
if(nums[i] != index) {
return index;
}
index++;
}
return len;
}
};
方法二代码:(find方法)
class Solution {
public:
int missingNumber(vector<int>& nums) {
int len = nums.size();
for(int i=0; i<len; i++){
auto it = find(nums.begin(), nums.end(), i);
if(it == nums.end()){
return i;
}
}
return len;
}
};
方法三代码:(用一个新数组)
class Solution {
public:
int missingNumber(vector<int>& nums) {
int len = nums.size();
vector<int> vt(len+1, 0);
for(int i=0; i<len; i++){
vt[nums[i]] = 1;
}
for(int i=0; i<len+1; i++){
if(vt[i] == 0){
return i;
}
}
return 0; //这个返回值只是为了有返回,其实不起作用
}
};