leetcode 287. Find the Duplicate Number(python)

Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-In Event, click to view the event details .

describe

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number.

You must solve the problem without modifying the array nums and uses only constant extra space.

Example 1:

Input: nums = [1,3,4,2,2]
Output: 2
复制代码

Example 2:

Input: nums = [3,1,3,4,2]
Output: 3
复制代码

Note:

1 <= n <= 10^5
nums.length == n + 1
1 <= nums[i] <= n
All the integers in nums appear only once except for precisely one integer which appears two or more times.
复制代码

Parse

According to the meaning of the question, given an integer array nums containing n + 1 integers, each of which is in the range [1, n]. There is only one repeating number in nums and we are required to return this repeating number. The title also requires that we have to solve the problem without modifying the array nums, and using only constant extra space. In fact, after reading the question, we found that this question is a sub-question, the difficulty is not like Medium, but Eazy.

In fact, although this problem requires space constraints, it is fine if you don’t need constant extra space. My idea to solve this problem at the time was to use a dictionary to count, and which number appeared 2 times and returned it directly. The time complexity of this method is O(N) and the space complexity is O(N).

In fact, there are many other solutions. For example, we can sort nums, and then traverse whether the current element is equal to the next element. If it is equal, it means that it is a duplicate element and returns it directly. The time complexity of this solution is O(N) and the space complexity is O(1). This solution is clearly more in line with the meaning of the question.

From the statistics of the results, the time-consuming and memory usage of the latter solution is significantly less than that of the former solution.

answer

class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        for i in range(len(nums)-1):
            if nums[i] == nums[i+1]:
                return nums[i]
复制代码

operation result

Runtime: 644 ms, faster than 71.73% of Python online submissions for Find the Duplicate Number.
Memory Usage: 25.2 MB, less than 57.18% of Python online submissions for Find the Duplicate Number.
复制代码

Original title link

leetcode.com/problems/fi…

Your support is my greatest motivation

おすすめ

転載: juejin.im/post/7080695421718233124