Re: [閒聊] 每日LeetCode已回收
26. Remove Duplicates from Sorted Array
給予你一個已排序整數陣列nums,我們要做兩件事:
1.找出該陣列共有幾個不重複數字。
2.若不重複數字有k個,我們需修改nums的前k個元素使其每個數字都不重複。
(題目額外要求空間複雜度需是O(1))
Example:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explaintion:nums共有5個不重複數字,修改原nums的前k個元素。
思路:
1.令當前不重複數字curr為第一個數字,下個插入位置index為1。
2.從第二個數字開始遍歷,如果遇到和curr不同的數字表示遇到不重複的數字,更新curr
並插入到index的位置,持續第二步驟直到遍歷完。
3.返回index。
Java Code:
------------------------------------
class Solution {
public int removeDuplicates(int[] nums) {
int curr = nums[0];
int index = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != curr) {
nums[index++] = nums[i];
curr = nums[i];
}
}
return index;
}
}
------------------------------------
這題倒讚好多喔 我猜是一堆人沒閱讀題目根本不知道要修改原陣列(函數只返回一個int)
--
https://i.imgur.com/7bZXdBG.jpg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.159.111.108 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1668138803.A.E13.html
推
11/11 11:58,
3年前
, 1F
11/11 11:58, 1F
→
11/11 12:00,
3年前
, 2F
11/11 12:00, 2F
→
11/11 12:01,
3年前
, 3F
11/11 12:01, 3F
推
11/11 12:18,
3年前
, 4F
11/11 12:18, 4F
推
11/11 15:06,
3年前
, 5F
11/11 15:06, 5F
推
11/11 16:39,
3年前
, 6F
11/11 16:39, 6F
推
11/11 21:06,
3年前
, 7F
11/11 21:06, 7F
→
11/12 15:04,
3年前
, 8F
11/12 15:04, 8F
討論串 (同標題文章)
完整討論串 (本文為第 96 之 719 篇):