268 Missing Number 缺失數(shù)字
Description:
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
Example :
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?
題目描述:
給定一個(gè)包含 0, 1, 2, ..., n 中 n 個(gè)數(shù)的序列喜颁,找出 0 .. n 中沒有出現(xiàn)在序列中的那個(gè)數(shù)苍鲜。
示例 :
示例 1:
輸入: [3,0,1]
輸出: 2
示例 2:
輸入: [9,6,4,2,3,5,7,0,1]
輸出: 8
說明:
你的算法應(yīng)具有線性時(shí)間復(fù)雜度碾牌。你能否僅使用額外常數(shù)空間來實(shí)現(xiàn)?
思路:
- 參考LeetCode #136 Single Number 只出現(xiàn)一次的數(shù)字的思路, 利用異或
- 求和, 與通項(xiàng)公式求取的值相差的數(shù)就是丟失的數(shù)
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
int missingNumber(vector<int>& nums)
{
return ((nums.size() * nums.size() + nums.size()) >> 1) - accumulate(nums.begin(), nums.end(), 0);
}
};
Java:
class Solution {
public int missingNumber(int[] nums) {
int result = nums.length;
for (int i = 0; i < nums.length; i++) {
result ^= i;
result ^= nums[i];
}
return result;
}
}
Python:
class Solution:
def missingNumber(self, nums: List[int]) -> int:
return ((len(nums) ** 2 + len(nums)) >> 1) - sum(nums)