You are given an array with all the numbers from 1 to N appearing exactly once, except for two number that is missing. How can you find the missing number in O(N) time and O(1) space?
You can return the missing numbers in any order.
Example 1:
Input: [1]
Output: [2,3]
Example 2:
Input: [2,3]
Output: [1,4]
Note:
nums.length <= 30000
--------------------------------------------------------------------------
以前碰到过这类题目,要求O(1)的空间复杂度,用 异或 来做。
结果现在做的时候忘记用异或具体要怎么做了,只好网上找答案,这次应该能记住了。。
然后看评论区看到另一种解法,比异或简单,也更易理解,特此记录一下。
Answer:
public int[] missingTwo(int[] nums) {
int[] ans = new int[2];
int N = nums.length + 2;
int sum = (N + 1) * N / 2; // 1~N求和
for(int i=0; i<nums.length; i++){
sum -= nums[i];
} //现在sum为缺失的两数之和
int threshold = sum / 2; //缺失的两个数不同,因此一个小于threshold, 一个大于threshold.
int temp = 0;
for(int i=0; i<nums.length; i++){
if(nums[i] <= threshold){
temp += nums[i]; //对数组中小于等于threshold的数求和
}
}
int ans1 = (1 + threshold) * threshold / 2 - temp; //缺失的第一个数
int ans2 = sum - ans1; //缺失的第二个数
ans[0] = ans1;
ans[1] = ans2;
return ans;
}