Remove Duplicates from Sorted Array
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns 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.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.
Internally you can think of this:
//nums is passed in by reference.(i.e, without making a copy)
int len = removeDuplicates(nums);
//any modification to nums in your function would be known by the caller.
//using the length returned by your function, it prints the first len elements.
for(int i = 0; i < len; i++) {
print(nums[i]);
}
今天的每日一题是一道简单难度的题目,要求是删除有序数组中的重复项(咦?怎么看起来这么眼熟?)看了一下,之前有做过一道类似的题目,也是有序数组元素的原地去重。只不过那个题目要求一个元素可以重复两次,而今天的题目是只能出现一次。但是这两道题的思路是一样的,定义快慢两个指针,快指针用来遍历输入数组,慢指针用来记录被保留的元素当前所处的位置。
删除有序数组中的重复项II
话不多说,直接上代码:
/**
* @author: LittleWang
* @date: 2021/4/18
* @description:
*/
public class Solution {
public int removeDuplicates(int[] nums) {
int fast = 1, slow = 1; //因为数组的第一个元素一定会被保留,所以索引直接从1开始
if(nums.length == 0 || nums.length == 1){ //判断特殊情况,输入数组长度为0或1时直接返回原数组
return nums.length;
}
while(fast < nums.length) {
if(nums[fast] != nums[fast-1]) { //如果当前元素不重复,就把当前元素赋值给慢指针所指的位置,同时快慢指针+1
nums[slow++] = nums[fast++];
}
else { //否则慢指针不动,快指针继续向后遍历
fast++;
}
}
return slow;
}
}
提交结果: