268 Missing Number
Bit Manipulation, Array, Hash Table, Math, Binary Search, Sorting ·Problem Statement
link: LeetCode.cn LeetCode
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Example:
Input: nums = [0,1]
Output: 2
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Solution Approach
To find the missing number in the given array, employ the concept of the sum of consecutive integers. Calculate the expected sum of the range [0, n], subtract the actual sum of array elements, and return the result. The formula (n + 1) * n // 2 efficiently computes the expected sum.
Algorithm
- Calculate the expected sum of the range [0, n] using the formula (n + 1) * n // 2, where n is the length of the array plus one.
- Find the actual sum of the elements in the array using the sum(nums) function. Subtract the actual sum from the expected sum to obtain the missing number in the array.
- Return the result as the final output.
Implement
class Solution:
def missingNumber(self, nums: List[int]) -> int:
return (len(nums) + 1) * len(nums)//2 - sum(nums)