[LeetCode]71. 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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
解法1:不考虑常数空间复杂度的限制,一个简单的解法是初始化一个n+1个元素的vector<int> v(n+1,-1),然后遍历输入数组,将v对应下标处的值设为输入数组当前值。最后对v遍历一遍看哪个下标处的值还是-1即可。时间空间复杂度都是O(n)。可以用bitset来压缩空间复杂度。
class Solution { public: int missingNumber(vector<int>& nums) { int n = nums.size(); vector<int> vi(n + 1, -1); for (int i = 0; i < n; ++i) vi[nums[i]] = nums[i]; for (int i = 0; i < n + 1; ++i) if (vi[i] == -1) return i; return n; } };
解法2:先将输入数组排序,然后扫描一遍找到第一个不在位置的元素即可。时间空间复杂度取决于所用排序算法。
class Solution { public: int missingNumber(vector<int>& nums) { sort(nums.begin(), nums.end()); for(int i = 0; i < nums.size(); ++i) if(nums[i] != i) return i; return nums.size(); } };
解法3:因为这n个数是从[0,n]中抽取的,因此分别求和:sum1=(0+n)*(n+1)/2为所有n-1个数的和,遍历输入数组可以求得抽取的n个数的和sum2,两者相减即得缺失的那个数。时间复杂度O(n),空间复杂度O(1)。
class Solution { public: int missingNumber(vector<int>& nums) { int n = nums.size(); int sum1 = n * (n + 1) / 2; int sum2 = accumulate(nums.begin(), nums.end(), 0); return sum1 - sum2; } };
解法4:结合题目Single Number可以想到基于位操作的解法:将输入数组与[0,n]异或,最后得到的值即是缺失的那个。因为输入数组元素为n个,任何数异或0都是它本身,因此我们只需从1开始到n结束即可。时间复杂度O(n),空间复杂度O(1)。
class Solution { public: int missingNumber(vector<int>& nums) { int res = 0; for(int i = 1; i <= nums.size(); ++i) res ^= i ^ nums[i - 1]; return res; } };