王廷瑋|數位醫療|智慧醫療: 26. Remove Duplicates from Sorted Array WFU

2024年7月2日 星期二

26. Remove Duplicates from Sorted Array

26. Remove Duplicates from Sorted Array


給定一個按非遞減順序排序的整數數組 nums,就地移除重複項,使每個唯一元素只出現一次。元素的相對順序應保持不變。然後返回 nums 中唯一元素的數量。

將 nums 中唯一元素的數量視為 k,為了被接受,你需要做以下幾件事:更改數組 nums,使得 nums 的前 k 個元素包含按初始順序排列的唯一元素。
nums 剩餘的元素不重要,數組的大小也不重要。
返回 k。

自定義測試:

測試將使用以下代碼來檢查你的解決方案:

int[] nums = [...]; // 輸入數組 int[] expectedNums = [...]; // 正確長度的預期答案 int k = removeDuplicates(nums); // 調用你的實現 assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; }

如果所有斷言都通過,那麼你的解決方案將被接受。

範例 1:

輸入:nums = [1,1,2] 輸出:2, nums = [1,2,_] 解釋:你的函數應返回 k = 2,nums 的前兩個元素分別為 1 和 2。 返回的 k 之後的元素無關緊要(因此它們是下劃線)。


Python


from typing import List

class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
# Initialize the write pointer
write_index = 1
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
nums[write_index] = nums[i]
write_index += 1
return write_index

17.95MB, 76ms


C++


#include <vector>

using namespace std;

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
// Initialize the write pointer
int write_index = 1;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] != nums[i - 1]) {
nums[write_index] = nums[i];
++write_index;
}
}
return write_index;
}
};

21.01MB, 8ms


Javascript

/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
if (nums.length === 0) {
return 0;
}
// Initialize the write pointer
let writeIndex = 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] !== nums[i - 1]) {
nums[writeIndex] = nums[i];
writeIndex++;
}
}
return writeIndex;
};

52.73MB, 56ms