項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 search-input 尚未註冊或是沒有一個 view.php 檔案.

【Leetcode】python – [16] 3Sum Closest 個人解法筆記

題目出處

16. 3Sum Closest

難度

medium

個人範例程式碼

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        if not nums or len(nums) < 3:
            return -1

        nums.sort()
        ans = float("inf")

        for idx, first_num in enumerate(nums):
            ans = self.two_sum(nums, target, ans, first_num, idx+1, len(nums)-1)    

        return ans

    def two_sum(self, nums, target, ans, first_num, left, right):
        while(left < right):
            if first_num + nums[left] + nums[right] == target:
                return target
            elif first_num + nums[left] + nums[right] < target:
                ans = self.find_closest(ans, first_num + nums[left] + nums[right], target)
                left += 1
            else: # if first_num + nums[left] + nums[right] > target:
                ans = self.find_closest(ans, first_num + nums[left] + nums[right], target)
                right -= 1
        else:
            return ans      

    def find_closest(self, a, b, target):
        if abs(a - target) <= abs(b - target):
            return a
        else:
            return b      

算法說明

這題有幾乎相同的類似題,可參考:

【Leetcode】python – [Google | Onsite] Two Sum – Closest to Target 個人解法筆記 (Lintcode – 533)

前者是 2Sum,這題更難改成 3Sum,但思路與 3Sum 大同小異

【Leetcode】python – [15] 3Sum 個人解法筆記 (updated: 2022/4/6)

最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解

input handling

處理 input 為 [] 或 len < 3 的情況,輸出 -1 。(題目沒說,但這邊先預留特殊狀況處理)

Boundary conditions

特別留意 3Sum 的搜尋條件,特別是 a <= b <= c 的處理部分 (可以看 3Sum 的文章)

Reference

⭐ Leetcode 解題紀錄 ⭐題型資料結構Python SolutionC++ SolutionNote
⭐BFS 相關題型 ⭐
104Maximum Depth of Binary TreeBFS (分層)Python
94Binary Tree Inorder TraversalBFS (分層)TreePython 內含 處理 Tree 樹問題的重點
102Binary Tree Level Order TraversalBFS (分層)TreePython
103Binary Tree Zigzag Level Order TraversalBFS (分層)TreePython
107Binary Tree Level Order Traversal IIBFS (分層)TreePython
133Clone GraphBFS (分層)GraphPython Graph 的基本操作 #重要題型
127Word LadderBFS (分層), DFSGraphPython
[Lint] 127Topological SortingBFS (拓撲)Python
內有 indegree, outdegree 介紹 #重要題型
207Course ScheduleBFS (拓樸)GraphPython
210Course Schedule IIBFS (拓樸)GraphPython