Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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:
Given nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It doesn't matter what you leave beyond the returned length.
Given nums = [0,0,1,1,1,1,2,3,3],
Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 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.
解釋下題目:
刪掉一個(gè)數(shù)組中重復(fù)的元素棚饵,使重復(fù)的元素最多只有兩個(gè)
1. 從頭開始判斷
實(shí)際耗時(shí):1ms
public int removeDuplicates(int[] nums) {
int i = 0;
for (int number : nums) {
if (i < 2 || number > nums[i - 2]) {
nums[i] = number;
i++;
}
}
return i;
}
??思路就是前兩個(gè)是肯定要放進(jìn)去的,然后之后因?yàn)槭怯行虻模匀绻麛?shù)字比它前兩個(gè)大谁不,那么說明是不同的贼涩,就應(yīng)該賦值亡驰,否則就應(yīng)該繼續(xù)下去毒返。