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

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

[LeetCode]15.3Sum

2019-11-14 10:35:01
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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

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

算法:

排序,O(nlogn)如果是2Sum,那么只需要兩個(gè)指針(lo, hi),一個(gè)從左一個(gè)從右,向中間搜索。
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外加上了一層循環(huán)
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
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 库伦旗| 通江县| 琼中| 津市市| 五常市| 德江县| 嫩江县| 泸水县| 礼泉县| 自贡市| 德江县| 缙云县| 察雅县| 漳平市| 阜新市| 昭觉县| 林口县| 绥中县| 克拉玛依市| 鄂温| 莲花县| 阳春市| 沙雅县| 伊春市| 卓尼县| 富宁县| 伊吾县| 东乡族自治县| 台前县| 通许县| 新乡县| 安平县| 射阳县| 金堂县| 饶阳县| 左贡县| 承德市| 达尔| 萍乡市| 水富县| 双峰县|