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?

解答:
一开始我的思始很简单,排序,查找:

public int missingNumber(int[] nums) {
    if (nums == null || nums.length == 0) return 0;
    int result = 0;
    
    Arrays.sort(nums);
    for (int i = 0; i < nums.length; i++) {
        if (result != nums[i]) {
            return result;
        }
        result++;
    }
    return nums.length;
}

但是可以用xor的triky方法,因为只有一个missing number,所以可以把其它所有的数都配好对,剩下这个就是我们要找的number:

public int missingNumber(int[] nums) {
    int xor = 0, i = 0;
    
    //这里很triky喔,因为只少了一个数,举个例子:
    //nums: 1, 3, 4
    //   i: 1, 2, 3, (4)
    //所以当我们把这些数xor的时候,唯一一个剩下的就是2, missing的这个数
    
    for (i = 0; i < nums.length; i++) {
        xor = xor ^ i ^ nums[i];
    }
    
    return xor ^ i;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值