当前位置:网站首页>LeetCode#268. Missing numbers

LeetCode#268. Missing numbers

2022-07-06 15:22:00 Rufeng ZHHH

subject :

Given an inclusion [0, n]  in  n  Array of Numbers nums , find [0, n] The number that doesn't appear in the array in this range .

Example 1:

Input :nums = [3,0,1]
Output :2
explain :n = 3, Because there is 3 A digital , So all the numbers are in range [0,3] Inside .2 It's the missing number , Because it didn't show up in nums in .
Example 2:

Input :nums = [0,1]
Output :2
explain :n = 2, Because there is 2 A digital , So all the numbers are in range [0,2] Inside .2 It's the missing number , Because it didn't show up in nums in .
Example 3:

Input :nums = [9,6,4,2,3,5,7,0,1]
Output :8
explain :n = 9, Because there is 9 A digital , So all the numbers are in range [0,9] Inside .8 It's the missing number , Because it didn't show up in nums in .
Example 4:

Input :nums = [0]
Output :1
explain :n = 1, Because there is 1 A digital , So all the numbers are in range [0,1] Inside .1 It's the missing number , Because it didn't show up in nums in .

 

Tips :

n == nums.length
1 <= n <= 104
0 <= nums[i] <= n
nums All the numbers in are unique

source : Power button (LeetCode)
link : Power button

We can solve this problem by using the relevant knowledge of the arithmetic sequence , Relatively simple .

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        return int(len(nums)*(len(nums)+1)/2-sum(nums))

原网站

版权声明
本文为[Rufeng ZHHH]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131319092258.html