[LeetCode] 268. Missing Number

题目:https://leetcode.com/problems/missing-number/description/

题目

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?

题目大意

给一个数组nums 长度为 n ,其中n个数均不同 且都从 0,1,2,……,n中抽出。求 漏到的 那个元素。

要求 :

  1. 时间复杂度为 time(n)。
  2. 空间复杂度为 space(1)。

思路

方法一 求和法

求出 0,1,2,……,n的和,减去A 中数组的元素,可以得到 漏掉的元素。

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

方法二 xor

由于 a^ b^ b =a ,两个相同的数在 xor操作中 将不影响 原数。

将 0,1,2,……,n 和 数组nums的 所有元素 都进行 xor,最后的结果 便是 数组中漏掉的元素,因为该元素只在 xor式子中出现了 一次。

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

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/84293054