Leetcode 题目解析之 Missing Number

2022-01-09 11:39:29 浏览数 (1)

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?

既然是0~n只差其中一个数,不如再次加入0~n的序列,这样就和LeetCode 136 Single Number一样了,missing number只出现一次,其余都是出现两次。

代码语言:txt复制
    public int missingNumber(int[] nums) {
        int rt = nums.length;
        for (int i = 0; i < nums.length; i  ) {
            rt = rt ^ nums[i] ^ i;
        }
        return rt;
    }

0 人点赞