Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
給定一個(gè)有序的整數(shù)數(shù)列友酱,每個(gè)數(shù)最多只能出現(xiàn)兩次,然后去除多余的數(shù)洞渔,把剩下的數(shù)排在原數(shù)組的前面,并返回新數(shù)列的長度
這雖然是個(gè)中等題凛膏,不過難度不大冠绢,唯一需要多考慮的就是在原數(shù)組前面排列新的數(shù)組
For example
Given sorted array 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. It doesn't matter what you leave beyond the new length.
My Solution
(Java) Version 1 Time: 1ms:
做出的方法還是各種立flag,囤躁,沒什么多解釋的,就是遍歷一遍福铅,然后跳過重復(fù)多的萝毛,然后符合標(biāo)準(zhǔn)的就放到前面去,甚至都不用交換
public class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length == 0)
return 0;
int count = 1, tempcount = 1, temp = nums[0], index = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == temp) {
if (tempcount < 2) {
tempcount++;
nums[index] = nums[i];
index++;
count++;
}
} else {
temp = nums[i];
tempcount = 1;
nums[index] = nums[i];
index++;
count++;
}
}
return count;
}
}
(Java) Version 2 Time: 0ms (By StefanPochmann):
別人家的姿勢水平就是高很多滑黔,能如此簡單地解答笆包,關(guān)鍵在于題目中給出的是有序數(shù)列,所以后面的數(shù)一定是比前面的大略荡,或者說不同庵佣,就不用考慮后面還會(huì)有和前面相同數(shù)的情況
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}