268. Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3]
return 2
.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
class Solution { public: int missingNumber(vector<int>& nums) { int res = 0; int numsSize = nums.size(); bool isFind = false; for(int i=0;i<numsSize;i++){ while(nums[i]!=i){ if(nums[i] >= numsSize){ isFind = true; res = i; break; } swap(nums[i],nums[nums[i]]); } } return isFind ? res:numsSize; } };
此外,还有很多好方法,例如,
法1.
先计算sum1=0+1+2+3+...+n,
再计算sum2 = nums[0]+nums[1]+...+nums[n-1];
然后sum1-sum2就是缺失的那个数
法2.排序二分
41. First Missing Positive
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0]
return 3
,
and [3,4,-1,1]
return 2
.
Your algorithm should run in O(n) time and uses constant space.
如果数组中的数是按照数该在的位置摆放(数i摆放在数组i的位置),那么很容易就能获得第一个缺失的正数。
所以我们先调整数组数的位置,令下标为i的位置存放数i。
再遍历一遍数组,如果nums[i]!=i,说明该位置的数缺失。
class Solution { public: int firstMissingPositive(vector<int>& nums) { int n = nums.size(); int i = 0 ; while(i<n){ while( nums[i]!= i+1 ){ if(nums[i]<=0 || nums[i]>n || nums[i]==nums[nums[i]-1]){ break; } swap(nums[i],nums[nums[i]-1]); } i++; } i = 0; while(i<n && nums[i] == i+1){ i++; } return i+1; } };