[LeetCode] 268. Missing Number
阿新 • • 發佈:2018-12-16
題目: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中抽出。求 漏到的 那個元素。
要求 :
- 時間複雜度為 time(n)。
- 空間複雜度為 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;
}
}