package main.java.simple;
/**
- https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/description/?envType=study-plan-v2&envId=top-interview-150
- <p>
- 給你一個(gè)有序數(shù)組 nums 彭雾,請(qǐng)你 原地 刪除重復(fù)出現(xiàn)的元素炼鞠,使得出現(xiàn)次數(shù)超過(guò)兩次的元素只出現(xiàn)兩次 账锹,返回刪除后數(shù)組的新長(zhǎng)度。
- <p>
- 不要使用額外的數(shù)組空間秒梅,你必須在 原地 修改輸入數(shù)組 并在使用 O(1) 額外空間的條件下完成。
*/
class RemoveDuplicates2 {
public static int removeDuplicates(int[] nums) {
int left = 0;
int right = 0;
int tag = 0;
while (right < nums.length) {
if (nums[right] != nums[left]) {
left = right;
}
if (right - left < 2 || nums[right] != nums[left]) {
nums[tag] = nums[left];
tag++;
}
right++;
}
return tag;
}
public static void main(String[] args) {
System.out.println(removeDuplicates(new int[]{1, 1, 1, 2, 2, 3}));
System.out.println(removeDuplicates(new int[]{1}));
System.out.println(removeDuplicates(new int[]{2, 3, 4}));
}
}