问题:
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.
与上一个问题类似,只不过这里给定的是排好序的数组,同时要求修改为删除重复的元素。
思路:设置好标志位i,同时因为是排好序的数组,所以我们可以利用元素之间的大小不同这一特性去遍历。
class Solution {
public int removeDuplicates(int[] nums) {//注意不仅仅需要返回长度,还要保留好数组。
if(nums.length==0)
return 0;
int i=0;
for(int n:nums)
{
if(i==0||n>nums[i-1])
nums[i++]=n;
}
return i;
}
}

本文介绍了一种在不使用额外空间的情况下从已排序数组中删除重复元素的方法,并确保了数组元素只出现一次,同时返回新的有效数组长度。通过一个简单的Java实现示例,展示了如何在遍历过程中有效地更新数组。
4037

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



