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

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

題目出處

難度

medium

個人範例程式碼 – two pointers

from typing import (
    List,
)

class Solution:
    """
    @param nums: an integer array
    @param target: An integer
    @return: the difference between the sum and the target
    """
    def two_sum_closest(self, nums: List[int], target: int) -> int:
        if not nums:
            return -1

        ans = float("inf") # biggest value

        nums.sort()
        start, end = 0, len(nums) - 1
        while(start < end):
            print(ans)
            if target - (nums[start] + nums[end]) == 0:
                return 0 # early return
            elif target > (nums[start] + nums[end]): # sum is smaller than target
                ans = min(ans, target - (nums[start] + nums[end]))
                start += 1
            else: # target < (nums[start] + nums[end]) # sum is bigger than target
                ans = min(ans, (nums[start] + nums[end]) - target)
                end -= 1
        else:
            return ans

算法說明

先 sort 後以 two pointers 處理,這邊容易有個思考上的盲點,
就是如果「減去負數」的處理不就「數值會變更大」了嗎?

  • 這部分可以看下圖:

我們會發現其實 target 的移動與結果影響不大。
就算是”減去””負的”,也只是「往離 target」更遠的方向前進。

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

input handling

處理 input 為 [] 的情況,輸出 -1。 (題目沒說,但做為表示找不到結果)

Boundary conditions

結束條件

相向相交時,start < end

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
[Lint] 892Alien DictionaryBFS (拓樸)GraphPython
[Lint] 431Connected Component in Undirected GraphBFS (連通塊)Graph