LeetCode 658:寻找K个最接近元素中comp变量未按预期更新
解决LeetCode寻找K个最接近元素问题时的比较逻辑错误排查
问题描述
我正在解决LeetCode第658题「寻找K个最接近元素」,题目要求从给定数组arr中返回长度为k的子数组,包含k个与给定值x最接近的元素。我已完成所有边界条件和约束判断,但在比较逻辑部分遇到问题:
我创建了空列表a,当a的长度不等于k时,遍历数组并比较abs(i - x) < abs(comp - x),comp初始值为arr[0],预期当比较成立时将comp更新为i,但实际该变量未按预期更新。测试用例为:arr = [1,1,1,10,10,10],k = 4,x = 9。
重点排查的代码片段
a = [] comp = arr[0] iteration = 0 i_index = 0 while len(a) != k: for i in arr: comp_1 = abs(i - x) comp_2 = abs(comp - x) if comp_1 < comp_2: comp == i print(f"comp: {comp}") arr.pop(arr.index(comp)) a.append(comp) return a
完整代码
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: # Constraints if k < 1 or k > len(arr): return "k must be greater than 0 and less than the arr length" if len(arr) < 1 or len(arr) > 10**4: return "arr length must be greater than 0 and less than 10^4" if x > 10**4: return "x must be less than 10^4" if sorted(arr) != arr: return "arr must be sorted" for i in arr: if i < -10**4: return "arr item cannot be less than -10^4" #Variables 1 begin = arr[:k] end = arr[-k:] # Base cases if len(arr) == k: return arr if x < arr[0]: return begin elif x > arr[-1]: return end try: x_index = arr.index(x) half_k = int(k/2) #if k == x and x_index != None: # return [x] # Captures all other lists that begin at arr[0] or end at arr[-1] if x_index - half_k < 0: return begin elif x_index + half_k > len(arr) - 1: return end # Create list out of interior of arr if necessary else: return arr[x_index - half_k : x_index + half_k] # Means x is not in arr except ValueError: a = [] comp = arr[0] iteration = 0 i_index = 0 while len(a) != k: for i in arr: print(f"{iteration} - {i_index}:") print(f"i: {i}") print(f"comp_1: {abs(i - x)}") print(f"comp_2: {abs(comp - x)}") comp_1 = abs(i - x) comp_2 = abs(comp - x) if comp_1 < comp_2: comp == i print(f"comp: {comp}") i_index += 1 print("\n") iteration += 1 arr.pop(arr.index(comp)) a.append(comp) return a
内容的提问来源于stack exchange,提问作者Stoutish_goat
相关产品推荐
相关产品推荐

