题目:
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
大意:
给定一个排好序的数组,将数组中的重复元素去掉,相同的只保留一个,并且返回数组新的元素个数,不要创建一个新的数组来保存结果。在常量内存里解决这个问题。
思路:
设置两个标志位i,j,位置j和值和位置i的值不相同时,i++,将nums[j]的值赋给nums[i]。
代码:
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0 || nums.length == 1) {
return nums.length;
}
int i = 0;
for(int j = 1; j < nums.length; j++) {
if(nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i+1;
}
}