LeetCode 26 刪除排序陣列中的重複項

2022-06-05 06:30:07 字數 1032 閱讀 7936

給定乙個排序陣列,你需要在 原地 刪除重複出現的元素,使得每個元素只出現一次,返回移除後陣列的新長度。

不要使用額外的陣列空間,你必須在 原地 修改輸入陣列 並在使用 o(1) 額外空間的條件下完成。

輸入:  [1,1,2]

輸出: 2 #[1, 2]

輸入:   [1, 2, 2, 2, 3] 

輸出: 3 #[1, 2, 3]

原地替換,不能使用格外空間

特判 --> 小於2的陣列,返回本身

指標指向前兩位(current, next = 0, 1)

遍歷比較current 與 next

current == next : 相鄰相同,next = next + 1

current != next

若 next - current > 1: next 與 current 大於1,將next置換currentnums[current + 1] = nums[next]

next = next + 1

from typing import list

class solution:

def removeduplicates(self, nums: list[int]) -> int:

if len(nums) <= 1:

return len(nums)

current, next = 0, 1

while next < len(nums):

if nums[current] != nums[next]:

current = current + 1

nums[current] = nums[next] if (next - current) > 0 else nums[current]

next = next + 1

pass

return current + 1

leetcode - 26.刪除排序陣列中的重複項

LeetCode 26 刪除排序陣列中的重複項

給定乙個排序陣列,你需要在原地 刪除重複出現的元素,使得每個元素只出現一次,返回移除後陣列的新長度。不要使用額外的陣列空間,你必須在原地修改輸入陣列並在使用 o 1 額外空間的條件下完成。示例 1 給定陣列 nums 1,1,2 函式應該返回新的長度 2,並且原陣列 nums 的前兩個元素被修改為1...

leetcode26 刪除排序陣列中的重複項

給定乙個排序陣列,你需要在原地 刪除重複出現的元素,使得每個元素只出現一次,返回移除後陣列的新長度。不要使用額外的陣列空間,你必須在原地修改輸入陣列並在使用 o 1 額外空間的條件下完成 示例 1 給定陣列 nums 1,1,2 函式應該返回新的長度 2,並且原陣列 nums 的前兩個元素被修改為1...

LeetCode 26刪除排序陣列中的重複項

給定乙個排序陣列,你需要在原地刪除重複出現的元素,使得每個元素只出現一次,返回移除後陣列的新長度。不要使用額外的陣列空間,你必須在原地修改輸入陣列並在使用 o 1 額外空間的條件下完成。示例 1 給定陣列 nums 1,1,2 函式應該返回新的長度2,並且原陣列 nums 的前兩個元素被修改為1,2...