[Array]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?
思路:给出一个数组,该数组中的元素各不相同,找出数组中缺少的值并返回。
XOR
XOR在C语言中是位操作,异或。有一个非常神奇的用法:a^b^b=a,a^b^c^b^a=a^a^b^b^c=c可以交换顺序,随意组合,而且一般用于加密算法。也就是说这种方法对顺序没有要求。
int missingNumber(vector<int>& nums) { int result = 0; for (int i = 0; i < nums.size(); i++) result ^= nums[i]^(i+1); return result; /* int result = nums.size(); for(int i = 0; i < nums.size(); i++){ result ^= nums[i] ^ i; } return result; */ }
SUM
这个方法真的是应该最容易想到的,sum的类型设置应该为long,不然会溢出。
int missingNumber(vector<int >nums) { //sum int len = nums.size(); int sum = (0+len)*(len+1)/2; for(int i=0; i<len; i++) sum-=nums[i]; return sum; }
Binary Search
这种方法对一个数组进行二分查找,因为排序之后,下标和元素值应该是相互对应的,如果缺少某个值。
int missingNumber(vector<int >nums) { int left = 0, right = nums.size(), mid = (left+right)/2; while(left < right){ mid = (left+right)/2; if(num[mid] > mid) right = mid; else left = mid +1; } return left; }