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?

一刷
类似于寻找哪个数字只出现了一次,其它的都出现两次。
如果[0, 2, .., n-1]中间有一个数字miss, 数组长度n-1
那么每次与数组中的元素异或,与index异或,最后留下的数字为miss

public class Solution {
    public int missingNumber(int[] nums) {
        int res = 0;
        for(int i=0; i<nums.length; i++){
            res ^= i^nums[i];
        }
        res ^= nums.length;
        return res;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容