Leetcode学习笔记:#26. 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.
实现:
public int removeDuplicates(int[] nums){
int i = 1;
int j = 0;
for(;i < nums.length; i++){
if(nums[i] != nums[j]){
j++;
nums[j] = nums[i];
}
}
return j+1;
}
思路:
两个指针,一个j从0一个i从1开始,如果遇到相等的数字,则跳过,j指针不增加;若不是相等的,j自增1,把nums[i]赋值给nums[j]。