17.19. Missing Two LCCI

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;
       
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值