Day4- 15. 3Sum

今日题目:15. 3Sum(Medium)

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.

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

Example 2:
Input: nums = []
Output: []

Example 3:
Input: nums = [0]
Output: []

Constraints:

  • 0 <= nums.length <= 3000
  • -105 <= nums[i] <= 105

思路

(待补)(我已经太疲惫)

My solution:

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)

        if n == 0 or n==2: return []
        
        ans = []
        nums.sort()
        print(nums)
        i = 0
        for i in range(n-2):
            if nums[i] == nums[i-1] and i>0:
                continue
            j = i+1
            k = n-1
            temp = nums[j]+nums[k]
           
            while k>j:
                temp = nums[j] + nums[k]

                if temp > -nums[i]:
                    k-=1
                elif temp<-nums[i]:
                    j+=1
                else:
                    while nums[k] == nums[k - 1] and k > j:
                        k-=1
                    while nums[j] == nums[j + 1] and k > j:
                        j += 1
                    ans.append([nums[i],nums[j],nums[k]])
                    j+=1
                    k-=1
        return(ans)

Result

https://ithelp.ithome.com.tw/upload/images/20210919/20140843C1561VLqEH.png

题目不难,但是有很多details必须注意
如不注意
就会与我一样,耗费了一整个下午:))


<<:  Proxmox VE 储存基本配置

>>:  【Day 19】JavaScript 宣告和变数

成为工具人应有的工具包-27 ShellMenuView

ShellMenuView 今天一样来认识这个看 shell 外挂选单的工具(?) ShellMen...

Android Studio初学笔记-Day12-Spinner

Spinner选单 Spinner有快速选择选单中项目的功能,是个很常用的选择工具,不过spinne...

[Day 3] 一同面对焦虑吧!

焦虑感的来袭 不得不说,在有工作的情形下,一方面要努力完成现有的工作,另一方面还得焦虑自己是否能够真...

excel 内有病毒

想请问一下,公司用了本人一个 excel 档案已经几年了,一般也是自动化处理公司内部一些文件或报告类...

Python 学习笔记_装饰器(decorator) 与重试(retry)

这篇文章主要是在纪录 python decorator 的学习过程, 有错或是更好的写法的话,欢迎留...