0268. Missing Number (E)

Missing Number (E)

题目

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

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?


题意

给定一个长度为n的数组,从 0-n 这 n+1 个数中选取 n 个数填充入数组中,找到缺失的那一个数。

思路

交换法:第一次遍历数组,将nums[i]与下标为nums[i]的数进行交换,第二次遍历数组,如果遇到 i != nums[i],说明i就是缺失的数。

求和法:先求 0-n 的和,再求数组中数的和,相减就是缺失的数。

异或法:根据相同的数异或为0的性质, 将数组中所有数异或一遍,再将结果与 0-n 异或一遍,相同的数会互相抵消,得到的结果就是缺失的数。


代码实现

Java

交换

class Solution {
    public int missingNumber(int[] nums) {
        int i = 0;
        while (i < nums.length) {
            if (nums[i] >= nums.length || nums[i] == i) {
                i++;
            } else {
                swap(nums, i, nums[i]);
            }
        }
        for (int j = 0; j < nums.length; j++) {
            if (nums[j] != j) {
                return j;
            }
        }
        return nums.length;
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}

求和

class Solution {
    public int missingNumber(int[] nums) {
        int len = nums.length;
        int sum1 = (len + 1) * len / 2;
        int sum2 = 0;
        for (int num : nums) {
            sum2 += num;
        }
        return sum1 - sum2;
    }
}

异或

class Solution {
    public int missingNumber(int[] nums) {
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            res = res ^ nums[i] ^ (i + 1);
        }
        return res;
    }
}

JavaScript

/**
 * @param {number[]} nums
 * @return {number}
 */
var missingNumber = function (nums) {
  let i = 0;
  while (i < nums.length) {
    let j = nums[i]
    if (nums[i] === nums[j] || nums[i] === i) {
      i++
    } else {
      [nums[i], nums[j]] = [nums[j], nums[i]]
    }
  }
  i = 0
  while (i < nums.length) {
    if (i !== nums[i]) return i
    i++
  }
  return i
};
posted @ 2020-06-17 08:27  墨云黑  阅读(189)  评论(0编辑  收藏  举报