1. 程式人生 > >給定一個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重複的三元組

給定一個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重複的三元組

例如, 給定陣列 nums = [-1, 0, 1, 2, -1, -4],

滿足要求的三元組集合為:
[
[-1, 0, 1],
[-1, -1, 2]
]
解題思路:
開始採取遍歷陣列方式然後判斷遍歷的三個數的索引是否相同再做相加判斷
但是list.index()只返回資料在陣列中第一次出現時的索引,由於題目中給出的陣列中有相同的資料所以這種方式不可取
思索一會之後採取遍歷索引的方式
得出如下程式碼

def threeSum(self, nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
l = [] for a in range(len(nums)): for b in range(len(nums)): for c in range(len(nums)): if (a != b) and (a != c) and (b != c) and (nums[a] + nums[b] + nums[c] == 0): l.append(sorted([nums[a],nums[b],nums[c]])) return(list(list(t) for
t in(set([tuple(t) for t in l]))))