剑指offer————数组中的重复数字 python

题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

1.不需要额外空间,直接在原数组上修改;

def f(n,lst):
    for i in range(n):
        while i != lst[i]:
            if lst[i] != lst[lst[i]]:
                lst[lst[i]],lst[i] = lst[i],lst[lst[i]]
                print(a)
            else:
                return lst[i]

2.不能改动原数组,需要额外的空间开销;

def f2(n,lst):
    temp = [None for i in range(n)]
    for i in range(n):
        if temp[lst[i]]  != lst[i]:
            temp[lst[i]]  = lst[i]
            print(temp)
        else:
            return lst[i]
a = [2,3,1,0,2,5,3]
f2(6,a)

猜你喜欢

转载自blog.csdn.net/zh547368475/article/details/82811171