↓快轉到主要內容
  1. LeetCode/

LeetCode 611: Valid Triangle Number

·1 分鐘· ·
LeetCode Medium Array Two-Pointers Binary-Search Greedy
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2022-11-27

  • 提交紀錄:Wrong Answer → Accepted ×2

解題思路
#

排序之後,三角形只要檢查兩短邊之和大於最長邊(Two Pointers 模板四)。固定最長邊 k,i 從 0、j 從 k - 1 開始:

  • nums[i] + nums[j] > nums[k]:i 換成 i..j-1 任何一個都會更大,一次加 j - i 個,j 左移。
  • 否則 i 右移。

我的嘗試
#

第一版一次加的是 j - 1(打錯),例如 [4, 7, 9]:i = 0、j = 1 時應該加 1,這版加了 0,回傳 0。

正確解法
#

class Solution:
    def triangleNumber(self, nums: List[int]) -> int:
        nums.sort()
        res = 0
        for k in range(2, len(nums)):
            i, j = 0, k - 1
            while i < j:
                if nums[i] + nums[j] > nums[k]:
                    res += j - i
                    j -= 1
                else:
                    i += 1
        return res

複雜度
#

時間 O(n²),空間 O(1)(不算排序)。

要特別避免的錯誤
#

  • 一次加的是 j - i,不是 j - 1。

面試口說整理
#

排序後我固定最長邊,用左右指針找兩短邊:和夠大時左指針換成中間任何一個都成立,一次加上 j - i,右指針左移;不夠就左指針右移。時間 O(n²)。

相關文章

LeetCode 287: Find the Duplicate Number
·1 分鐘
LeetCode Medium Array Two-Pointers Binary-Search Bit-Manipulation
LeetCode 287 解題筆記:把 i -> nums[i] 看成鏈結串列,重複的值就是環的入口,用 Floyd 判圈;O(1) 空間、不改陣列
LeetCode 167: Two Sum II - Input Array Is Sorted
·1 分鐘
LeetCode Medium Array Two-Pointers Binary-Search
LeetCode 167 解題筆記:已排序,左右指針往中間走:和太大右指針左移,太小左指針右移;回傳的 index 從 1 開始
LeetCode 11: Container With Most Water
·1 分鐘
LeetCode Medium Array Two-Pointers Greedy
LeetCode 11 解題筆記:左右指針從兩端開始,每次移動比較矮的那一邊;移動高的那邊只會讓寬度變小、高度不會變高
LeetCode 275: H-Index II
·1 分鐘
LeetCode Medium Array Binary-Search
LeetCode 275 解題筆記:引用數已排序,找第一個 citations[i] >= n - i 的位置,答案是 n - i;用二分做到 O(log n)
LeetCode 540: Single Element in a Sorted Array
·1 分鐘
LeetCode Medium Array Binary-Search
LeetCode 540 解題筆記:單獨的那個出現之前,每一對都從偶數 index 開始;二分看偶數位置 mid 和 mid + 1 是否相同
LeetCode 324: Wiggle Sort II
·1 分鐘
LeetCode Medium Array Divide-and-Conquer Greedy Sorting
LeetCode 324 解題筆記:排序後分成小的一半和大的一半,各自反轉後交錯放:小的放偶數位置、大的放奇數位置