26. 刪除有序數(shù)組中的重復(fù)項
難度簡單2039收藏分享切換為英文接收動態(tài)反饋
給你一個有序數(shù)組 nums ,請你 原地 刪除重復(fù)出現(xiàn)的元素,使每個元素 只出現(xiàn)一次 ,返回刪除后數(shù)組的新長度。
不要使用額外的數(shù)組空間,你必須在 原地 修改輸入數(shù)組 并在使用 O(1) 額外空間的條件下完成。
說明:
為什么返回數(shù)值是整數(shù),但輸出的答案是數(shù)組呢?
請注意,輸入數(shù)組是以「引用」方式傳遞的,這意味著在函數(shù)里修改輸入數(shù)組對于調(diào)用者是可見的。
你可以想象內(nèi)部操作如下:
// nums 是以“引用”方式傳遞的。也就是說,不對實參做任何拷貝
int len = removeDuplicates(nums);
// 在函數(shù)里修改輸入數(shù)組對于調(diào)用者是可見的。
// 根據(jù)你的函數(shù)返回的長度, 它會打印出數(shù)組中 該長度范圍內(nèi) 的所有元素。
for (int i = 0; i < len; i++) {
print(nums[i]);
}
示例 1:
輸入:nums = [1,1,2]
輸出:2, nums = [1,2]
解釋:函數(shù)應(yīng)該返回新的長度 2 ,并且原數(shù)組 nums 的前兩個元素被修改為 1, 2 。不需要考慮數(shù)組中超出新長度后面的元素。
示例 2:
輸入:nums = [0,0,1,1,1,2,2,3,3,4]
輸出:5, nums = [0,1,2,3,4]
解釋:函數(shù)應(yīng)該返回新的長度 5 , 并且原數(shù)組 nums 的前五個元素被修改為 0, 1, 2, 3, 4 。不需要考慮數(shù)組中超出新長度后面的元素。
提示:
0 <= nums.length <= 3 * 104-104 <= nums[i] <= 104-
nums已按升序排列
- Remove Duplicates from Sorted Array
Easy
38316930Add to ListShare
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns 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.
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 a 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]);
}
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2]
Explanation: 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:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4]
Explanation: 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.
Constraints:
0 <= nums.length <= 3 * 104-104 <= nums[i] <= 104-
numsis sorted in ascending order.
解法: 雙指針
首先注意數(shù)組是有序的,那么重復(fù)的元素一定會相鄰。
要求刪除重復(fù)元素,實際上就是將不重復(fù)的元素移到數(shù)組的左側(cè)。
考慮用 2 個指針,一個在前記作 down,一個在后記作 cur,算法流程如下:
1.比較 down 和 cur 位置的元素是否相等。
如果相等,cur 后移 1 位
如果不相等,將 cur 位置的元素復(fù)制到 down+1 位置上,down 后移一位,cur 后移 1 位
重復(fù)上述過程,直到 cur 等于數(shù)組長度。
返回 p + 1,即為新數(shù)組長度。
class Solution {
public static int removeDuplicates(int[] nums) {
if (nums == null) {
return 0;
}
if (nums.length < 2) {
return nums.length;
}
int done = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[done]) {
nums[++done] = nums[i];
}
}
return done + 1;
}
}
