from typing import List class Solution: def gcdSort(self, nums: List[int]) -> bool: # 并查集 def find(x): if parent[x] != x: parent[x] = find(parent[x]) return parent[x] def union(x, y): parent[find(x)] = find(y) # 获取一个数的所有质因数 def get_prime_factors(n): factors = set() i = 2 while i * i <= n: while n % i == 0: factors.add(i) n //= i i += 1 if n > 1: factors.add(n) return factors # 初始化并查集 max_num = max(nums) parent = list(range(max_num + 1)) # 对每个数字,将其与其质因数连接 for num in nums: for prime in get_prime_factors(num): union(num, prime) # 检查排序后的数组是否可以通过交换得到 sorted_nums = sorted(nums) for i in range(len(nums)): if find(nums[i]) != find(sorted_nums[i]): return False return True