分析圖示:
/**
* 給定一個排序數組,你需要在原地刪除重複出現的元素,使得每個元素只出現一次,返回移除後數組的新長度。
* 不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。
* @author mtreellen
* @create 2019-10-16-22:48
*/
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = new int[]{0,0,1,1,1,2,2,3,3,4};
System.out.println(removeDuplicates(arr));
}
public static int removeDuplicates(int[] nums) {
if(nums == null || nums.length == 1){
return nums.length;
}
int i = 0;
int j = 1;
for(j = 1; j < nums.length;){
if(nums[i] == nums[j]){
j++;
}else{
i++;
nums[i] = nums[j];
j++;
}
}
return i + 1;
}
}