268. 缺失数字_剑指offer_面试题53 - II

问题

给定一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 … n 中没有出现在序列中的那个数。
例子

在这里插入图片描述

思路

  • 方法1

    i = 0 i = n i i = 0 i = n 1 n u m s [ i ] \sum_{i=0}^{i=n}i-\sum_{i=0}^{i=n-1}nums[i]

  • 方法2

    下标为0~n-1,在加上n,将其全部异或,再把数组所有的数一块异或,得到的哪个数就是缺失的数,因为其他数都出现了两次

代码

    public int missingNumber(int[] nums) {
        //方法1
        int res=0;
        int len = nums.length;
        for(int n:nums)
            res+=n;
        
        return len*(len+1)/2-res;
        //方法2
        int res=nums.length;
        for(int i=0; i<nums.length; i++)
        {
            res^=i;
            res^=nums[i];
        }
        return res;

    }

发布了151 篇原创文章 · 获赞 7 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/puspos/article/details/104804919
今日推荐