题目:https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
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.
题目大意:
有序数组去重复,返回去重后数组的长度
/**有序数组去重复
* @param nums 需要去重的有序数组
* @return 去重后数组的长度
*/
public static int removeDuplicates(int[] nums) {
if(nums.length==0){
return 0;
}
int len=0;
int cur=0;
while (cur<nums.length) {
if(nums[cur]==nums[len]){
cur++;
}else {
//给数组重排序
nums[++len]=nums[cur++];
}
}
return len+1;
}