LeetCode 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.

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?

 


 

找到数组中缺失的数字,有两种优质的解法:

 

解法一(高斯求和):

这个方法是我在前边刷题的时候一直想于找到重复数字的方法,但是同一个数字重复次数一旦超过两次就不能使用了。遇到这道题的时候仔细分析题意,要求从[0, n]中随机删除掉一个数字组成元素数量为n的数组中,找到被删除的数字。

利用上边的条件可以得到核心思路:在n个元素和不会超过 Integer.MAX_VALUE 的情况下,可以先对0到n区间中的所有元素求和,然后减去当前数组nums中的数字,最后得到的值即为缺失的值。

 

解法二(位操作):

一个更加简练的解法,我们知道位操作异或(XOR)有两个特点:

  1. 两个相同的数字进行异或为0
  2. 0与任意一个非0数字异或结果为非0数字

并且异或运算满足交换律结合律,所以我们可以使用 [0, n] 中所有的数字与nums中所有的数字做异或运算,最后得到的值就是缺失的数字。举例如下:

假设nums为[0, 1, 3, 4],索引与值的对应表如下:

索引0123
0134

缺失的值  = (0 \wedge 0) \wedge (1 \wedge 1) \wedge (2 \wedge 3) \wedge (3 \wedge 4) \wedge (4) = (0 \wedge 0) \wedge (1 \wedge 1) \wedge (2) \wedge (3 \wedge 3) \wedge (4 \wedge 4)

 


 

AC代码:

class Solution {
    public int missingNumber(int[] nums) {
        int numLen = nums.length;

        int sum = numLen * (numLen + 1) / 2;
        for (int elem : nums) {
            sum -= elem;
        }

        return sum;
    }
}

 


如有错误,欢迎指摘。欢迎通过左上角的“向TA提问”按钮问我问题,我将竭力解答你的疑惑。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值