今日份leetcode 26. Remove Duplicates from Sorted Array
Description:
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.
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.
这道题目是要将数组中重复的数去掉,只输出不重复的数。其实仔细想想这道题和前面做过的把指定的数移除 27. Remove Element 和把0后移 283. Move Zeroes 的题目的解题思想是一样的。当时智商下降没有想到…
我开始做的思路是:扫描数组,找到相同的数记录位置,接着往下找直到不再相同再记录另一个位置。然后把后面的元素统一往前移。循环下去。
class Solution {
public int removeDuplicates(int[] nums) {
int newlength = nums.length;
for(int i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1])
newlength--; //记录数组中不重复元素的个数,最后用来输出
}
for(int i=0;i<nums.length-1;i++){
int a = i; //记录某个值的重复元素中,最后一个重复元素的位置,如{1,1,1,2,3}中的第三个1
int b = i; //记录后面元素要往前移动到的位置
while(nums[i]==nums[a+1]){
a++;
if(a+1>=nums.length) //防止数组溢出
break;
}
for(int j=a+1;j<=nums.length-1;j++){ //往前移动
nums[b+1]=nums[j];
b++;
}
}
return newlength;
}
}
这种方法耗时太高,131ms左右。
下面是一种更好的办法,找不相同的元素,用两个指针,一个用来记录不相同元素的索引位置,另一个用来记录要把不相同元素前移放入的位置(指针值连续)。这就是我上面所说的与leetcode 27,283相同的思路。都是从反面入手,找不相同的元素,而我是直接找相同的元素然后处理,这是比较麻烦的。唉唉,啥时候才能学以致用啊。。。
class Solution {
public int removeDuplicates(int[] A) {
if (A.length==0) return 0;
int j=0; //记录把不相同元素要往前移动的位置,从0开始连续的
for (int i=0; i<A.length; i++)
if (A[i]!=A[j]) A[++j]=A[i];
return ++j;
}
}
时间复杂度O(n),耗时大约7ms。
今天新学了一种酷酷的拍照新姿势,哈哈哈,没茅台!