iT邦幫忙

2025 iThome 鐵人賽

DAY 26
0
自我挑戰組

leetcode系列 第 26

leetcode 26. Remove Duplicates from Sorted Array

  • 分享至 

  • xImage
  •  

題目:
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
Return k.
給定一個以非降序nums排序的整數數組,就地刪除重複項,使得每個唯一元素只出現一次。元素的相對順序應保持不變。然後傳回中唯一元素的數量。nums

考慮到的獨特元素的數量,為了nums被k接受,您需要做以下事情:

修改數組nums,使 的前幾個k元素nums依其初始出現的順序包含唯一元素nums。 的其餘元素nums以及 的大小並不重要nums。
返回k。
https://ithelp.ithome.com.tw/upload/images/20251010/20169340jwXJisZBgt.png
解題思路 — 雙指針法(Two Pointers)

陣列已排序 → 重複元素會相鄰。

使用兩個指標:

slow:指向結果陣列的最後一個「不重複元素」位置。

fast:用來遍歷整個陣列。

如果 nums[fast] != nums[slow],代表找到新的元素,將它放到 slow+1 位置。

遍歷完成後,slow+1 就是新的陣列長度。
https://ithelp.ithome.com.tw/upload/images/20251010/20169340CtWtQXsMdb.png


上一篇
leetcode 25. Reverse Nodes in k-Group
下一篇
leetcode 27. Remove Element
系列文
leetcode30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言