Interview question 17.19. Two disappearing numbers
Given an array containing all integers from 1 to N, but two numbers are missing. Can you find them in O(N) time using only O(1) space?
Both numbers can be returned in any order.
Example 1:
输入: [1]
输出: [2,3]
Example 2:
输入: [2,3]
输出: [1,4]
hint:
- nums.length <= 30000
Answer ideas:
- 1. The array nums from 1 to N is missing two elements, then N=nums.length+2
- 2. The sum of the two missing numbers sumOfTwo = sum(1…N)-sum(nums)
- 3. Remember ave=sumOfTwo/2. Because the two missing numbers are not equal, one is less than or equal to ave, and the other is greater than or equal to ave.
- 4. Only sum the elements less than or equal to ave, and the first missing number is sum(1...ave)-sum (in nums, the elements less than or equal to ave)
- 5. The second missing number: sumOfTwo minus the first missing number
class Solution {
/*
1.从1到N的数组nums,缺失了两个元素,那么N=nums.length+2
2.缺失的两个数字的和sumOfTwo = sum(1...N)-sum(nums)
3.记住ave=sumOfTwo/2.因为缺失的两个数字不相等,所以一个小于等于ave,一个大于等于ave
4.只对小于等于ave的元素求和,得到第一个缺失数字
sum(1..ave)-sum(nums中,小于等于ave的元素)
5.第二个缺失的数字:sumOfTwo-第一个缺失的数字
*/
public int[] missingTwo(int[] nums) {
int sum = 0;
for(int i=0;i<nums.length;i++){
sum=sum+nums[i];//将原数组中所有数字求和
}
//int n = nums.length+2; //数字1到n等差数列求和为(n+1)n/2
int sumOfTwo = (nums.length+2+1)*(nums.length+2)/2 - sum;//找到那俩个缺失数字的和
int aveOfTwo = sumOfTwo/2; //计算缺失两个缺失数字的平均和aveOfTwo
sum = 0;
for(int i=0;i<nums.length;i++){
//这里判断条件写成i<nums.length&&nums[i]<=aveOfTwo会有问题?????
if(nums[i]<=aveOfTwo){
sum=sum+nums[i]; //再对数组中小于等于aveOfTwo数组进行求和
}
}
int []arr = new int[2]; //创建大小为2的数组arr
arr[0] = (aveOfTwo+1)*aveOfTwo/2 - sum;//缺失数字中较小的数字smallNum = sum(1..aveOfTwo)-sum(nums中小于aveOfTwo的数字),并将其放入a[0]中
arr[1] = sumOfTwo - arr[0]; //较大的数字=sumOfTwo-arr[0]
return arr; //最后返回数组arr即可
}
}