Remove Duplicates from Sorted Array:从排列后的数组中删除重复元素
考察数组的基本操作:
class Solution { public int removeDuplicates(int[] nums) { if (nums==null || nums.length==0) return 0; int index = 1; for(int i =1; i<nums.length; i++){ if(nums[i]!=nums[i-1]){ nums[index] = nums[i]; index++; } } return index; } public static void main(String[] args) { int[] arr = { 1, 2, 2, 3, 3 }; arr = removeDuplicates(arr); System.out.println(arr.length); } }
Remove Duplicates from Sorted Array II (Java)
For example, given sorted array A = [1,1,1,2,2,3], your function should return length = 5, and A is now [1,1,2,2,3].
最多允许两个重复,输出结果数组。
解法1:当counter是2时,就直接跳过即可,否则说明元素出现次数没有超,继续放入结果数组,若遇到新元素则重置counter。总体算法只需要扫描一次数组,所以时间上是O(n),空间上只需要维护一个index和counter,所以是O(1)。
public int removeDuplicates(int[] A) { if(A==null || A.length==0) return 0; int idx = 0; int count = 0; for(int i=1;i<A.length;i++) { if(A[i]==A[i-1]) { count++; if(count>=3) continue; } else { count = 1; } A[idx++]=A[i]; } return idx; }
解法二:
public class Solution { public int removeDuplicates(int[] A) { if (A.length <= 2) return A.length; int prev = 1; // point to previous int curr = 2; // point to current while (curr < A.length) { if (A[curr] == A[prev] && A[curr] == A[prev - 1]) { curr++; } else { prev++; A[prev] = A[curr]; curr++; } } return prev + 1; } }