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?
题意:这道题给我们n个数字,是0到n之间的数但是有一个数字去掉了,让我们寻找这个数字,要求线性的时间复杂度和常数级的空间复杂度。
思路:
1.假设他们没有缺,求出他们的和,再减去他们真实的和就可以求出缺少的值;
2.XOR运算,a^b^b=a 现在还没怎么明白代码;
3.二分查找法,在给定数组有序的情况下。我们首先要对数组排序,然后我们用二分查找法算出中间元素的下标,然后用元素值和下标值之间做对比,如果元素值大于下标值,则说明缺失的数字在左边,此时将right赋为mid,反之则将left赋为mid+1。
1.代码实现:
class Solution { public int missingNumber(int[] nums) { int i,sum=0; int len = nums.length; for(int num :nums){ sum+=num; } return len*(len+1)/2-sum; } }
2.代码实现:
public int missingNumber(int[] nums) { int xor = 0, i = 0; for (i = 0; i < nums.length; i++) { xor = xor ^ i ^ nums[i]; } return xor ^ i; }
3.代码实现:
class Solution { public: int missingNumber(vector<int>& nums) { sort(nums.begin(), nums.end()); int left = 0, right = nums.size(); while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] > mid) right = mid; else left = mid + 1; } return right; } };