Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Example 1:
Input: [3,0,1] Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1] Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
//Time: O(n), Space: O(1)
//Approach 1 : 用前n+1项和公式减去nums里面的每一个值,剩下的就是missing number
public int missingNumber(int[] nums) { if (nums == null || nums.length == 0) { return -1; } int result = 0; for (int i = 0; i < nums.length; i++) { result += nums[i]; } return nums.length * (nums.length + 1) / 2 - result; //Approach 2: XOR public int missingNumber(int[] nums) { if (nums == null || nums.length == 0) { return -1; } int result = 0; for (int i = 0; i < nums.length; i++) { result = result ^ i ^ nums[i]; } return result ^ nums.length;//最后不要忘记异或最后一个数 } //Approach 3: 如果是排序好的数组,可以用二分法time为O(logn), 否则排序time是O(nlogn) 代码略