Leetcode 第268题Missing Number

来源:互联网 发布:福建广电网络电视客服 编辑:程序博客网 时间:2024/05/16 19:30

题目: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与a异或那么结果是a;如果a与a异或那么结果是0
    • 所以把数组中的所有数字相异或;再将正确的数字排序异或;最后的结果就是缺失的数字
  • 方法三:数列求和法
    • 因为数组中的数字是等差为1的数列,那么将给的数组的每个数字相加;
    • 把数组中的长度加一到0求和;
    • 两个和的差值就是缺失的数字

代码:

  • C++:
    方法二代码:
class Solution {public:    int missingNumber(vector<int>& nums) {        int l=nums.size();        int res=nums[0];        for(int i=1;i<l;i++)        {            res=res^nums[i];        }        for(int j=0;j<l+1;j++)        {            res=res^j;        }        return res;    }};

方法三代码:

class Solution {public:    int missingNumber(vector<int>& nums) {        int l=nums.size();        int res=nums[0];        int temp=0;        for(int i=1;i<l;i++)        {            res=res+nums[i];        }        for(int j=0;j<l+1;j++)        {            temp=temp+j;        }        return temp-res;    }};
0 0