268. Missing Number
- Total Accepted: 62408
- Total Submissions: 150160
- Difficulty: Medium
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?
思路:先排序再查找。
代码:
方法一:a^b^b=a以及异或操作的交换律。
1 class Solution { 2 public: 3 int missingNumber(vector<int>& nums) { 4 int i,Xor=0; 5 for(i=0;i<nums.size();i++){ 6 Xor=Xor^i^nums[i]; 7 } 8 return Xor^i; 9 } 10 };
方法二:对[0,n]求和后减去sum(nums[0],...,nums[n-1])。
1 class Solution { 2 public: 3 int missingNumber(vector<int>& nums) { 4 int i,sum=nums.size(); 5 for(i=0;i<nums.size();i++){ 6 sum+=i-nums[i]; 7 } 8 return sum; 9 } 10 };
方法三:二分查找。
1 class Solution { 2 public: 3 int missingNumber(vector<int>& nums) { 4 sort(nums.begin(),nums.end()); 5 int mid,left=0,right=nums.size()-1; 6 while(left<=right){ 7 mid=left+(right-left)/2; 8 if(nums[mid]>mid){ 9 right=mid-1; 10 }else{ 11 left=mid+1; 12 } 13 } 14 return left; 15 } 16 };
方法四:
1 class Solution { 2 public: 3 int missingNumber(vector<int>& nums) { 4 int i=0,res=1; 5 sort(nums.begin(),nums.end()); 6 while(i<nums.size()&&(res&1)^(nums[i]&1)){ 7 res=nums[i++]; 8 } 9 return i<nums.size()?nums[i]-1:i; 10 } 11 };