首页 > 解决方案 > `if i != _i and j != _j and k != _k:` 继续但报告第一次出现?

问题描述

我有这样一个条件检查逻辑:

if k not in {None, i, j}: #don't reproduce itself   
    if i != _i and j != _j and k != _k: 
        continue #remove the identical copies    
    result = [num_1, num_2, num_3]
output.append(result)

但是,此解决方案将跳过所有重复项,我想要一个类似的逻辑

if i != _i and j != _j and k != _k:  #continue but add the first occurrence to output.

怎么可能搞定?

leetcodes 中的代码

class Solution:
    def threeSum(self, nums, target: int=0) -> List[List[int]]:   
        lookup = {nums[i]:i for i in range(len(nums))} #overwrite from the high
        triplets = []
        triplets_set = set()

        for i in range(len(nums)):
            num_1 = nums[i]
            sub_target = target - num_1
            # logging.debug(f"level_1_lookup: {lookup}")

            for j in range(i+1, len(nums)):
                num_2 = nums[j] #
                _j = lookup[num_2] #
                _i = lookup[num_1]
                _k = j + 1

                num_3 = sub_target - num_2              
                k = lookup.get(num_3) #             

                if k not in {None, i, j}: #don't reproduce itself   

                    if i != _i and j != _j and k != _k: continue #remove the identical copies 

                    result = [num_1, num_2, num_3]
                    result.sort()
                    result = tuple(result)
                    triplets_set.add(result)

        triplets = [list(t) for t in triplets_set]
        return triplets    

标签: python

解决方案


只需检查output您已经附加result到的 ,看看它是否包含您正在寻找的三元组。像这样的东西:

output = []
for i,j,k in some_iterable:
    if not [i, j, k] in output:
        output.append(result)

或者,如果您将其output用于其他用途,您可以为此目的专用一个单独的变量,或者实现一个布尔标志,该标志开始FalseTrue在您添加一次时会转动。


推荐阅读