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

LeetCode 80: Remove Duplicates from Sorted Array II

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

基本資料
#

難易度: medium 第一次嘗試:2022-10-26

  • 提交紀錄:Wrong Answer ×3 → Runtime Error → Accepted ×4

解題思路
#

跟 LC 26 一樣用寫入指標(Two Pointers 模板五),只是允許兩個。新的數 x 可以寫,條件是 k < 2 或 x != nums[k - 2]:如果跟往前第二個一樣,代表已經寫了兩個。

我的嘗試
#

前幾版用計數器 c 記目前這個值出現幾次,i、j 兩個指標的更新條件很複雜,例如 [0, 0, 0] 回傳 3(應該是 2)、只有一個元素時回傳 0。

正確解法
#

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        k = 0
        for x in nums:
            if k < 2 or x != nums[k - 2]:
                nums[k] = x
                k += 1
        return k

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 比的是已經寫入的 nums[k - 2],不是原陣列的 nums[i - 2](可能已被覆寫)。

面試口說整理
#

每個值最多兩個,所以我用寫入指標,新的數跟寫入位置往前第二個不一樣才寫。這個寫法改成最多 m 個時只要把 2 換成 m。時間 O(n)。

相關文章

LeetCode 75: Sort Colors
·1 分鐘
LeetCode Medium Array Two-Pointers Sorting Quicksort
LeetCode 75 解題筆記:荷蘭國旗:low 左邊都是 0、high 右邊都是 2;遇到 2 換到 high 之後不要前進,換過來的數還沒檢查
LeetCode 31: Next Permutation
·1 分鐘
LeetCode Medium Array Two-Pointers
LeetCode 31 解題筆記:從右邊找第一個下降的位置 i,跟右邊比它大的最小值交換,再把 i 之後反轉;比較時要包含等於
LeetCode 11: Container With Most Water
·1 分鐘
LeetCode Medium Array Two-Pointers Greedy
LeetCode 11 解題筆記:左右指針從兩端開始,每次移動比較矮的那一邊;移動高的那邊只會讓寬度變小、高度不會變高
LeetCode 15: 3Sum
·2 分鐘
LeetCode Medium Array Two-Pointers Sorting
LeetCode 15 解題筆記:排序後固定第一個數,剩下用對撞指針找兩數和;三個位置都要跳過相同的值,才不會有重複的組合
LeetCode 16: 3Sum Closest
·1 分鐘
LeetCode Medium Array Two-Pointers Sorting
LeetCode 16 解題筆記:排序後固定一個數,對撞指針找另外兩個;比較的是和跟 target 的距離 abs(sum - target)
LeetCode 18: 4Sum
·1 分鐘
LeetCode Medium Array Two-Pointers Sorting
LeetCode 18 解題筆記:排序後兩層迴圈固定前兩個數,剩下用對撞指針;四個位置都要跳過相同的值