本文共 812 字,大约阅读时间需要 2 分钟。
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] 题意:在数组S中找到三个元素相加和为0,当然要去重 思路:采用快速排序法只排一次,每次取一个数x,问题转化为target-x的2sum问题 时间复杂度为O(n^2) 注意去重在三个地方: 第一个:每次取一个数,只将该元素后续的列表中查找target-x的2sum和; 第二个:每次取一个数,需要判断是否和前一个数重复(循环起始数除外),只有不重复才进行2sum计算,重复则continue 第三个:在进行2sum计算,若2sum的和等于target后,需要将左右指针移位,过滤后续重复元素,直到元素不重复再计算2sum之和 Runtime: 202 msclass Solution(object): ''' 快速排序,递归的思想 ''' def qksort(self,nums): if len(nums)<=1: return nums base=nums[0] left=[] right=[] for i in nums[1:]: if i
转载地址:http://icfin.baihongyu.com/