Leetcode 80) Remove Duplicates from Sorted Array II
in Algorithms
- Move Zero 의 다른 풀이 방법에 착안해서 풀면 된다!
class Solution {
public int removeDuplicates(int[] nums) {
int cnt=0;
int prev=nums[0];
int indChange=0;
for(int i=1;i<nums.length;i++){
if(prev==nums[i]){
cnt++;
}else{
cnt=0;
}
if(cnt>=2){
indChange++;
}
prev=nums[i];
nums[i-indChange]=nums[i];
}
int result = nums.length-indChange;
return result;
}
}
다른 풀이
class Solution {
public int removeDuplicates(int[] nums) {
int state=1;
int i=0,j=1;
while(j<nums.length){
if(nums[i]!=nums[j]){
state=1;
}
else if(nums[i]==nums[j]){
state++;
}
if(state<=2){
nums[++i]=nums[j];
}
j++;
}
return i+1;
}
}