題目描述: 給定一個排序數組,你需要在原地刪除重複出現的元素,使得每個元素最多出現兩次,返回移除後數組的新長度。
不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。
示例 1:
給定 nums = [1,1,1,2,2,3],
函數應返回新長度 length = 5, 並且原數組的前五個元素被修改爲 1, 1, 2, 2, 3 。
你不需要考慮數組中超出新長度後面的元素。
示例 2:
給定 nums = [0,0,1,1,1,1,2,3,3],
函數應返回新長度 length = 7, 並且原數組的前五個元素被修改爲 0, 0, 1, 1, 2, 3, 3 。
你不需要考慮數組中超出新長度後面的元素。
說明:
爲什麼返回數值是整數,但輸出的答案是數組呢?
請注意,輸入數組是以“引用”方式傳遞的,這意味着在函數裏修改輸入數組對於調用者是可見的。
你可以想象內部操作如下:
// nums 是以“引用”方式傳遞的。也就是說,不對實參做任何拷貝
int len = removeDuplicates(nums);
// 在函數裏修改輸入數組對於調用者是可見的。
// 根據你的函數返回的長度, 它會打印出數組中該長度範圍內的所有元素。
for (int i = 0; i < len; i++) {
print(nums[i]);
}
方法一:
刪除多餘的重複項
可以自己動手畫一畫
class Solution {
public int [] removelement(int [] nums,int i)
{
for(int p=i+1;p<nums.length;p++)
{
nums[p-1]=nums[p];
}
return nums;
}
public int removeDuplicates(int[] nums) {
int i=1;
int count=1;
int length=nums.length;
while(i<length)
{
if(nums[i]==nums[i-1])
{
count++;
if(count>2)
{
this.removelement(nums,i);
i--;
length--;
}
}else
{
count=1;
}
i++;
}
return length;
}
}
方法二:
利用雙指針覆蓋多餘的重複項
算法:
使用了兩個指針,i 是遍歷指針,指向當前遍歷的元素;j 指向下一個要覆蓋元素的位置。
- 我們用 count 記錄當前數字出現的次數。count 的最小計數始終爲 1。
- 我們從索引 1 開始一次處理一個數組元素。
- 若當前元素與前一個元素相同,即 nums[i]==nums[i-1],則 count++。若 count > 2,則說明遇到了多餘的重複項。在這種情況下,我們只向前移動 i,而 j 不動。
- 若 count <=2,則我們將 i 所指向的元素移動到 j 位置,並同時增加 i 和 j。
- 若當前元素與前一個元素不相同,即 nums[i] != nums[i - 1],說明遇到了新元素,則我們更新 count = 1,並且將該元素移動到 j 位置,並同時增加 i 和 j。
當數組遍歷完成,則返回 j。
java代碼實現
class Solution {
public int removeDuplicates(int[] nums) {
//
// Initialize the counter and the second pointer.
//
int j = 1, count = 1;
//
// Start from the second element of the array and process
// elements one by one.
//
for (int i = 1; i < nums.length; i++) {
//
// If the current element is a duplicate, increment the count.
//
if (nums[i] == nums[i - 1]) {
count++;
} else {
//
// Reset the count since we encountered a different element
// than the previous one.
//
count = 1;
}
//
// For a count <= 2, we copy the element over thus
// overwriting the element at index "j" in the array
//
if (count <= 2) {
nums[j++] = nums[i];
}
}
return j;
}
}