[LeetCode]268. Missing Number(求数组中缺失的元素)

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.
给定一个包含从0,1,2,…,n中取出的n个不同数字的数组,找到数组中缺少的元素。
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?
您的算法应该运行在线性运行时的复杂性O(n)。 你可以使用只有额外的常量空间复杂性实现它吗?O(1)

思路1:

  • 给数组排序,不缺少元素情况下数组中元素应该与其下标的值相等
  • 遍历数组,找出与其下标不相等的元素,即缺少的元素

代码1:
33ms

#include <algorithm>

int missingNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int res = 0;
        for(int i=0; i<nums.size(); i++){
            if(nums[i] != res)
                return res;
            res++;
        }
        return res;
    }

思路2:

  • n = nums.size()
  • 求出不缺少元素情况下数组中所有元素的和,即0~n的和
  • 首尾相加 * 长度的一半
  • 0+1+2+3+…+n => (n+0)((n+1)/2) => n(n+1)/2
  • 依次减去数组中的元素,最后剩下的就是缺少的那个数

代码2:
26ms

int missingNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int res = 0;
        for(int i=0; i<nums.size(); i++){
            if(nums[i] != res)
                return res;
            res++;
        }
        return res;
    }

思路3:

  • 首先了解几个公式a^a=0 ,a^b^a=b ,a^b^c^a^c=b
  • 例: nums[] = {0, 2, 1, 3, 5}
  • i = 0, 1, 2, 3, 4
  • x = 5 (若数组nums不缺少元素,最大数应该是nums.size()=5)
  • 程序结束后x值就是缺少的元素

代码3:
22ms

int missingNumber2(vector<int>& nums) {
        int x = nums.size();
        for(int i = 0;i<nums.size();i++){
            x = x ^ nums[i] ^ i;
        }
        return x;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值