Given a sorted array, 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 in place with constant memory.
For example,
Given input array 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 new length.
對(duì)于排序數(shù)組,相同的值一定是聚集在一起的。
我一開(kāi)始的想法是交換尾部和頭部而不是覆蓋,交換算法是不穩(wěn)定的,這意味著我破壞了原來(lái)的有序性,從而判斷一個(gè)部分是否含有一個(gè)VAL從常數(shù)時(shí)間(只要判斷部分的末尾是否等于VAL)成了線性。這是一種不佳的退化。
這和remove element是不同的 前者的判斷式子是O(1)(是否等于一個(gè)特定的值),而在這里,要判斷是否重復(fù)在交換的情況下變成了O(N).(因?yàn)榻粨Q破壞了排序性)。
下面這張寫法是和Remove Element 差不多的 說(shuō)實(shí)話 我也不知道自己為啥要這樣寫。這張完全沒(méi)有利用有序的信息,采用的是暴力搜索,O(N2),可能我當(dāng)時(shí)腦子進(jìn)水了。
class Solution {
public int removeDuplicates(int[] nums) {
if(nums==null||nums.length==0)
return 0 ;
if(nums.length==1)
return 1;
int pos1 = 1;
int pos2 = nums.length-1;
while(pos1<=pos2)
{
if(search(nums,nums[pos1],pos1-1))
{
int temp = nums[pos2];
nums[pos2]= nums[pos1];
nums[pos1]=temp;
pos2--;
}
else
{
pos1++;
}
}
Arrays.sort(nums,0,pos2);
return pos2+1;
}
private boolean search (int[] nums , int target , int end)
{
for(int i = 0;i<=end;i++)
{
if(nums[i]==target)
return true;
}
return false;
}
}