[数据结构][Python][经典题目]寻找最大排列问题

    xiaoxiao2025-04-15  42

    递归:

    def naive_max_perm(M,A=None): if A is None: A = set(range(len(M))) if len(A)==1:return A B = set(M[i] for i in A) C = A-B if C: A.remove(C.pop()) return naive_max_perm(M,A) return A """ a b c d e f g h 人 a b c d e f g h 座位 a - c, b - c, c - a, d - f, e - d, f - f, g - h, h - e 代表a想坐c这个位置,以此类推 """ M = [2,2,0,5,3,5,7,4] result_per = naive_max_perm(M) print(result_per) {0, 2, 5}

    结果a,c,f得以留在对垒中,而其他人不得不留在其不喜欢的座位上 但是时间复杂度是平方级。

    def max_perm(M): n = len(M) A = set(range(n)) count = [0]*n for i in M: count[i]+=1 Q = [i for i in A if count[i]==0] while Q: i=Q.pop() A.remove(i) j = M[i] count[j] -=1 if count[j]==0: Q.append(j) return A

    这个是线性级时间复杂度

    最新回复(0)