two sum / three sum / four sum

two sum

兩種常見方法

  1. 時(shí)間復(fù)雜度 O(n), 空間復(fù)雜度O(1)
# two pointer for sorted array
class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        # time: O(n)l space: O(1)
        numbers = sorted(numbers)
        l,r = 0, len(numbers)-1
        while l<r:
            if numbers[l]+numbers[r] < target:
                l+=1
            elif numbers[l]+numbers[r] > target:
                r-=1
            else:
                return (l+1,r+1)
  1. 時(shí)間復(fù)雜度 O(n), 空間復(fù)雜度O(n)
# hash 表的存在是為了更快的找到pair num的下標(biāo)
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        #build hashmap
        maps = {}
        for i,ele in enumerate(nums):
            remain = target - ele
            if remain in maps.keys():
                return (maps[remain],i)
            else:
                maps[ele] = i

three sum

description: find no duplicated triplet that sum to zero from array
重點(diǎn)在于如何去掉重復(fù)的triplet

  1. 很直接但也有效的方式
class Solution(object):
    def threeSum(self, nums):
        ans = set() 
        if len(nums) < 3: return ans 
        if nums.count(0) >= 3: ans.add((0,0,0)) 
        nums_set = set(nums)
        numMax, numMin = max(nums_set), min(nums_set)
        if numMax <= 0 or numMin >= 0: return ans
        # Split into two parts, positive and negative, so don't have to iterate the whole nums. It reduces about 70% time.
        setP = set(num for num in nums_set if (num > 0 and num <= -2 * numMin))
        setN = set(num for num in nums_set if (num < 0 and num >= -2 * numMax)) 
        count = collections.Counter(nums)
        for numP in setP:
            for numN in setN:
                numD=-numP-numN
                if numD in nums_set:
                    val=tuple(sorted([numD,numP,numN]))
                    # this step make sure that count num correctly
                    # 比如 numN = -1 只出現(xiàn)一次的話,上述操作可能會(huì)有(-1祖能,-1歉秫,2),
                    # 但是2<1會(huì)過濾掉這個(gè)答案养铸。
                    if val.count(numD)<=count[numD] and val.count(numP)<=count[numP] and val.count(numN)<=count[numN]:
                        ans.add(val)
        return ans
  1. 由于要考慮重復(fù)數(shù)字的情況雁芙,一個(gè)一個(gè)處理比較好,那么就從two pointer的two sum到three sum吧钞螟, 很容易想到O(n^2)的方法
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        solution_set = []
        nums = sorted(nums)
        print(nums)
        for i in range(len(nums)-2):
            if ( i == 0 or nums[i] != nums[i-1]):
                target = 0 - nums[i]
                low, high = i+1, len(nums)-1
                while(low < high):
                    if(nums[low]+nums[high] == target):
                        solution_set.append([nums[i],nums[low],nums[high]])
                        while(low < len(nums)-1  and nums[low] == nums[low+1]):
                            low += 1
                        while(high>=1 and nums[high] == nums[high-1]):
                            high -= 1
                        low += 1
                        high -= 1
                    elif(nums[low]+nums[high] < target):
                        low += 1
                    else:
                        high -= 1
                        
        return solution_set

four sum

說是four sum兔甘,實(shí)際上是k sum的問題了,如three sum很快就想到1個(gè)loop+(k-1)sum鳞滨,也就是(k-2)loop + two sum洞焙, 如何用遞歸的形式寫出這個(gè)通用算法呢?

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        nums = sorted(nums)
        print(nums)
        def kSum(start, k, target):
            tmp_set = []
            # if k is greater than left nums, return directly
            if k > len(nums)-start:
                return tmp_set
            # k smallest elements, k largets elements
            k_min,k_max = 0,0
            for i in range(start,start+k):
                k_min += nums[i]
                k_max += nums[-i+start-1]
            if k_min > target or k_max < target:
                return tmp_set
            elif k > 2:
                for i,ele in enumerate(nums[start:-k+1]):
                    # choose ele and skip duplicate value
                    if i == 0 or nums[start+i-1] != ele:
                        small_tmp_set = kSum(start+i+1,k-1,target-ele)
                        # add ele into tmp_set
                        #print(small_tmp_set)
                        if all(small_tmp_set) != 0:
                            for l in small_tmp_set:
                                tmp_set.append([ele]+l)
            elif k == 2:
                low , high = start, len(nums)-1
                while(low < high):
                    if(nums[low]+nums[high] == target):
                        tmp_set.append([nums[low],nums[high]])
                        while(low < len(nums)-1  and nums[low] == nums[low+1]):
                            low += 1
                        while(high>=1 and nums[high] == nums[high-1]):
                            high -= 1
                        low += 1
                        high -= 1
                    elif(nums[low]+nums[high] < target):
                        low += 1
                    else:
                        high -= 1
            #print('*',k,tmp_set)
            return tmp_set
        solution_set = kSum(0,4,target)
        return solution_set
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末拯啦,一起剝皮案震驚了整個(gè)濱河市澡匪,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌褒链,老刑警劉巖唁情,帶你破解...
    沈念sama閱讀 218,525評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異甫匹,居然都是意外死亡甸鸟,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來佃乘,“玉大人榕莺,你說我怎么就攤上這事±捍拢” “怎么了?”我有些...
    開封第一講書人閱讀 164,862評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵季惯,是天一觀的道長(zhǎng)吠各。 經(jīng)常有香客問我臀突,道長(zhǎng),這世上最難降的妖魔是什么贾漏? 我笑而不...
    開封第一講書人閱讀 58,728評(píng)論 1 294
  • 正文 為了忘掉前任候学,我火速辦了婚禮,結(jié)果婚禮上纵散,老公的妹妹穿的比我還像新娘梳码。我一直安慰自己,他們只是感情好伍掀,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,743評(píng)論 6 392
  • 文/花漫 我一把揭開白布掰茶。 她就那樣靜靜地躺著,像睡著了一般蜜笤。 火紅的嫁衣襯著肌膚如雪濒蒋。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,590評(píng)論 1 305
  • 那天把兔,我揣著相機(jī)與錄音沪伙,去河邊找鬼。 笑死县好,一個(gè)胖子當(dāng)著我的面吹牛围橡,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播缕贡,決...
    沈念sama閱讀 40,330評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼翁授,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了善绎?” 一聲冷哼從身側(cè)響起黔漂,我...
    開封第一講書人閱讀 39,244評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎禀酱,沒想到半個(gè)月后炬守,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,693評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡剂跟,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,885評(píng)論 3 336
  • 正文 我和宋清朗相戀三年减途,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片曹洽。...
    茶點(diǎn)故事閱讀 40,001評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡鳍置,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出送淆,到底是詐尸還是另有隱情税产,我是刑警寧澤,帶...
    沈念sama閱讀 35,723評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站辟拷,受9級(jí)特大地震影響撞羽,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜衫冻,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,343評(píng)論 3 330
  • 文/蒙蒙 一诀紊、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧隅俘,春花似錦邻奠、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至颜骤,卻和暖如春唧喉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背忍抽。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評(píng)論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留董朝,地道東北人鸠项。 一個(gè)月前我還...
    沈念sama閱讀 48,191評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像子姜,于是被迫代替她去往敵國和親祟绊。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,955評(píng)論 2 355