国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

[LeetCode]15.3Sum

2019-11-14 10:01:28
字體:
來源:轉載
供稿:網友

這道題在春節假期期間做的,實在沒有心思做,自己只會暴力算法,也就是三層嵌套循環的O(n^3)的算法。

網上有此類問題的統一算法,k sum,假期也只了解了3Sum的解法,核心思想是先排序,后使用兩個指針(其實就是左右索引)將復雜度降到了O(n^2)

算法:

排序,O(nlogn)如果是2Sum,那么只需要兩個指針(lo, hi),一個從左一個從右,向中間搜索。
while lo < hi:    if sums[lo] + sums[hi] == target:        result.append([sums[lo], sums[hi]])        lo += 1        hi -= 1        while sums[lo] == sums[lo - 1]:            lo += 1        while sums[hi] == sums[hi + 1]:            hi -= 1    elif sums[lo] + sums[hi] < target:        lo += 1    else:        hi -= 1

3Sum是在2Sum外加上了一層循環
class Solution(object):    def threeSum(self, nums):        """        :type nums: List[int]        :rtype: List[List[int]]        """        # nums = list(set(nums))        # PRint nums        length = len(nums)        result = []        if nums == None or length < 3:            return result        nums.sort()        for x in xrange(0, length - 2):            if nums[x] > 0:                break            else:                if x == 0 or nums[x] > nums[x - 1]:                    left = x + 1                    right = length - 1                    while left < right:                        if nums[x] + nums[left] + nums[right] == 0:                            if [nums[x], nums[left], nums[right]] not in result:                                result.append(                                    [nums[x], nums[left], nums[right]])                            left += 1                            right -= 1                            while left < right and nums[left] == nums[left - 1]:                                left += 1                            while left < right and nums[right] == nums[right + 1]:                                right -= 1                        elif nums[x] + nums[left] + nums[right] < 0:                            left += 1                        else:                            right -= 1        return result
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 扶风县| 大石桥市| 大同市| 新宁县| 贵德县| 秦安县| 行唐县| 江孜县| 开鲁县| 射阳县| 兴仁县| 平谷区| 天台县| 赤峰市| 平顺县| 水富县| 报价| 灵宝市| 彭阳县| 新和县| 靖安县| 梅州市| 桦南县| 鄯善县| 宁乡县| 滨州市| 姜堰市| 夏津县| 尤溪县| 金堂县| 吉安县| 虹口区| 炎陵县| 淳安县| 恩平市| 余姚市| 肇庆市| 龙山县| 西畴县| 玛曲县| 科技|