【LeetCode 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.

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

思路:

  1. 排序,第一个位置和数字不对应的下标就是那个缺失数字。
  2. 求数组和,求0-n的和,两者之差就是缺失数字。
  3. 异或。原数组和0-n所有数字异或,结果就是缺失数字。

代码

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int len = nums.size();
        int result = 0;
        for (int i=0; i<len; ++i) {
            int temp = nums[i] ^ i;
            result ^= temp;
        }
        result ^= len;
        return result;
    }
};

感觉自己的脑子像生锈了一样,转不动。
今天也是懒散的开始。

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/89915270