Title description:
A set of consecutive integers starting from 0, but one of the numbers is missing. Please output this number.
输入:[0, 4, 3, 1, 5]
输出:2
Problem-solving ideas:
- Traverse and calculate the sum of array elements to get sum;
- Accumulate the subscripts from 0 to get sum1;
- The missing number is sum1+n-sum;
Code:
class Solution:
def Find_lost(self, nums):
sum, sum1 = 0, 0
n = len(nums)
for i in range(len(nums)):
sum += nums[i]
sum1 += i
result = sum1 + n - sum
return result
s = Solution()
nums = [0, 4, 3, 1, 5]
print(s.Find_lost(nums))