Question
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.
Answer
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
for(int j =0;j<nums.length;j++){
if(nums[j] !=nums[i]){
i++;
nums[j]=nums[i];
}
}
reuturn i+1;
}
}
本文介绍了一种在不使用额外空间的情况下,对已排序数组进行原地删除重复元素的方法,确保每个元素只出现一次,并返回新长度。通过修改输入数组实现O(1)额外内存消耗,展示了具体的Java实现代码。
1105

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



