26 Remove Duplicates from Sorted Array 刪除排序數(shù)組中的重復(fù)項(xiàng)
Description:
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example:
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
題目描述:
給定一個(gè)排序數(shù)組,你需要在原地刪除重復(fù)出現(xiàn)的元素,使得每個(gè)元素只出現(xiàn)一次,返回移除后數(shù)組的新長(zhǎng)度。
不要使用額外的數(shù)組空間,你必須在原地修改輸入數(shù)組并在使用 O(1) 額外空間的條件下完成。
示例:
示例 1:
給定數(shù)組 nums = [1,1,2],
函數(shù)應(yīng)該返回新的長(zhǎng)度 2, 并且原數(shù)組 nums 的前兩個(gè)元素被修改為 1, 2。
你不需要考慮數(shù)組中超出新長(zhǎng)度后面的元素。
示例 2:
給定 nums = [0,0,1,1,1,2,2,3,3,4],
函數(shù)應(yīng)該返回新的長(zhǎng)度 5, 并且原數(shù)組 nums 的前五個(gè)元素被修改為 0, 1, 2, 3, 4。
你不需要考慮數(shù)組中超出新長(zhǎng)度后面的元素。
說(shuō)明:
為什么返回?cái)?shù)值是整數(shù),但輸出的答案是數(shù)組呢?
請(qǐng)注意,輸入數(shù)組是以“引用”方式傳遞的,這意味著在函數(shù)里修改輸入數(shù)組對(duì)于調(diào)用者是可見(jiàn)的。
你可以想象內(nèi)部操作如下:
// nums 是以“引用”方式傳遞的。也就是說(shuō),不對(duì)實(shí)參做任何拷貝
int len = removeDuplicates(nums);
// 在函數(shù)里修改輸入數(shù)組對(duì)于調(diào)用者是可見(jiàn)的。
// 根據(jù)你的函數(shù)返回的長(zhǎng)度, 它會(huì)打印出數(shù)組中該長(zhǎng)度范圍內(nèi)的所有元素。
for (int i = 0; i < len; i++) {
print(nums[i]);
}
思路:
當(dāng)數(shù)組為空的時(shí)候返回0; 維護(hù)一個(gè)長(zhǎng)度, 遍歷數(shù)組找到不同值替換.
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (!nums.size()) return 0;
int result = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != nums[result]) nums[++result] = nums[i];
}
return ++result;
}
};
Java:
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int result = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[result] != nums[i]) nums[++result] = nums[i];
}
return ++result;
}
}
Python:
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
result = 0
for i in range(len(nums)):
if nums[i] != nums[result]:
result += 1
nums[result] = nums[i]
return result + 1