0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【LeetCode】15. 3Sum 解いてみた【Medium】

Posted at

問題の概要

与えられた配列から3つたしたら0になる組み合わせを全て返す

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]

Example 2:

Input: nums = [0,1,1]
Output: []

最初に考えた解き方

・組み合わせは--+,++-,-+0の3種類
これはコードにいれてない

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        l, r = 0, len(nums)-1
        res = []
        while l <= r-2:
            start = l
            m = l+1
            while l <= r-2:
                while m < r:
                    lNum = nums[l]
                    mNum = nums[m]
                    rNum = nums[r]
                    if lNum + mNum + rNum == 0:
                        res.append([lNum, mNum, rNum])
                    m += 1
                r -= 1
                l = start
        return res

何がよくなかったか?

いろいろとあるが、重複をリストにしてからチェックしようと考えていたが、ソートすれば計算する前にはじけた

解き方

Two Pointers

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        res = []
        nums.sort()

        for i, a in enumerate(nums):
            if a > 0:
                break

            if i > 0 and a == nums[i - 1]:
                continue

            l, r = i + 1, len(nums) - 1
            while l < r:
                threeSum = a + nums[l] + nums[r]
                if threeSum > 0:
                    r -= 1
                elif threeSum < 0:
                    l += 1
                else:
                    res.append([a, nums[l], nums[r]])
                    l += 1
                    r -= 1
                    while nums[l] == nums[l - 1] and l < r:
                        l += 1
                        
        return res

できたきがする

前にやったことが応用できていれば

参考資料

おわりに

つかえそうだと思ったら使おう

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?