- Remove Duplicates from Sorted Array
Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.
Example 1:
Given 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 returned length.
题目翻译:
给定一个有序数组,原地删除重复元素,使得每个元素只出现一次,并返回新的长度。
不为另一个数组分配额外空间,必须用常量内存做到这一点。
例如,
给定输入数组 A = [1,1,2],
函数应返回长度 = 2,A现在是[1,2]。
解题思路
题解方法是双指针,一个指针i只记录唯一的元素的并且帮助记录长度,一个指针 j 往前找。
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length==0)
return 0;
int i= 0;
for(int j=1;j<nums.length;j++){
if(nums[j]!=nums[i]){
i++;
nums[i]=nums[j];
}
}
return i+1;
}
}