[Offer] array to prove safety duplicate numbers - Python realization

Description] [Title
in an array of length n, where all numbers are in the range 0 to n-1. Some digital array is duplicated, but do not know how many numbers are duplicated. Do not know each digit is repeated several times. Please find an array of any one of the duplicate numbers. For example, if the length of the input array 7 {2,3,1,0,2,5,3}, then the corresponding output of the first 2 repeating digits.
[Problem-solving ideas]
Method One: establish hash table
time complexity: O (n)
space complexity: O (n)
Order to open an array to store the number of times each number appears, it is easy to identify repeat numbers, Python code is implemented as follows:

# -*- coding:utf-8 -*-
class Solution:
    # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
    # 函数返回True/False
    def duplicate(self, numbers, duplication):
        # write code here
        cnt = [0 for _ in range(len(numbers))]
        for item in numbers:
            if cnt[item] == 0:
                cnt[item] += 1
            else :
                duplication[0] = item
                return True
        return False

Method two: Homing digital
time complexity: O (n)
complexity of space: O (1)
since the length of the array is n, and each digital size are between 0 to n-1, so that each number in position pos in the array should be equal to this number, when this does not mean pos has equal numbers and figure numbers and this number should have been in position, the figure is the repetition number; when this number is not equal and pos when this number should have been numbers and this number is not equal to the position, this figure should be switched to its position. Python implemented in code as follows:

# -*- coding:utf-8 -*-
class Solution:
    # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
    # 函数返回True/False
    def duplicate(self, numbers, duplication):
        # write code here
        pos = 0
        while pos < len(numbers):
            if pos != numbers[pos]:
                # 当pos不等于这个数字且这个数字本来应该在的位置上有和这个数字相等的数字时,这个数字即为重复的数字
                if numbers[pos] == numbers[numbers[pos]]:
                    duplication[0] = numbers[pos]
                    return True
                # 当pos不等于这个数字且这个数字本来应该在的位置上的数字和这个数字不相等时,把这个数字交换到它应在的位置上
                else:
                    numbers[numbers[pos]], numbers[pos] = numbers[pos], numbers[numbers[pos]]
            else:
                pos += 1
        return False
Published 26 original articles · won praise 0 · Views 287

Guess you like

Origin blog.csdn.net/qq_36643449/article/details/104520438