一、问题描述
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.
二、问题分析
使用两个索引。
三、算法代码
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0){
return 0;
}
int cur = 0;
for(int index = 1; index <= nums. length - 1; index++){
if(nums[cur] != nums[index]){
nums[++cur] = nums[index];
}
}
return cur + 1;
}
}
本文介绍了一个高效的算法,用于在不使用额外空间的情况下去除已排序数组中的重复元素,并返回去除重复项后的数组长度。该方法通过双指针技术实现,其中一个指针负责跟踪当前最后一个不重复的元素位置,另一个指针遍历数组以寻找新的不重复元素。

289

被折叠的 条评论
为什么被折叠?



