原题链接: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
1. 题目介绍
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.
给出一个已经排好序的数组。移除其中的重复元素。使得每一个元素只出现1次,不要使用另外数组的多余空间,空间复杂度为O(1)。
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.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5,
with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
2. 解题思路-双指针法
双指针法是一种非常常见的方法,特别适合用于已经排序的数组中。
使用 left 和 right 两个指针,每当 nums[ right ] != nums[ left ]时,就使用 nums[ right ] 的值替代 nums[ left+1 ] 的值。 之后将left的值加1。而当 nums[ right ] == nums[ left ] 时,说明数字重复了,right +1 跳过即可。
相当于从0 到 left 的数字都是去除了重复的数字。而left ~ right之间的数字是重复的,需要想办法跳过他们,并且把 right 之后不重复的数的值复制到 left 处。
实现代码
class Solution {
public int removeDuplicates(int[] nums) {
int length = nums.length;
if(length == 0) {
return 0;
}
int left =0;
for(int right = 1; right<length ; right++) {
if(nums[right] != nums[left]) {
nums[left+1] = nums[right];
left ++;
}
}
return left + 1 ;
}
}
下面这个代码是我一开始想到的思路,速度比上面的方法慢。时间复杂度O(n log(n) )。我是将所有重复的数都改成int类型的最大值,然后对整个数组进行排序,最后取数组前面不是最大值的所有数就行了。
实现代码
class Solution {
public int removeDuplicates(int[] nums) {
int length = nums.length;
if(length == 0) {
return 0;
}
int left =0;
int Count = 1;
for(int i = 1;i<length;i++) {
if(nums[i] != nums[left]) {
left = i;
Count ++;
continue;
}
//nums[i] == nums[left]的情况
nums[i] = Integer.MAX_VALUE;
}
Arrays.sort(nums);
return Count;
}
}