Find missing numbers

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:

  1. Traverse and calculate the sum of array elements to get sum;
  2. Accumulate the subscripts from 0 to get sum1;
  3. 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))

Guess you like

Origin blog.csdn.net/weixin_43283397/article/details/110819429