[LeetCode] 268. Missing Number

论坛 期权论坛 脚本     
匿名技术用户   2021-1-7 09:42   110   0

题目:

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?

答案:

编程之美上有一道题很经典的题叫“快速找出机器故障”,概括地说就是有一个数组的数字全部都出现了两次,只有一个只出现了一次,让我们找到这个数字。最经典的思路就是使用异或(XOR),求数组中所有的数的异或。因为a&a = 0; 0&a = a,所以只有那个出现了一次的数字最终会被保留下来。

所以这道题也可以借用这种思想:

只要数组中所有的数求异或,再对0,1,2,...,nums.length求异或就好了。

参考代码:

public class Solution {
    public int missingNumber(int[] nums) {
        int xor = 0;
        for (int i = 0; i < nums.length; i++) {
            xor ^= nums[i] ^ i;
        }
        
        xor ^= nums.length;
        
        return xor;
    }
}

类似问题:


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP