1. 程式人生 > >LeetCode——Remove Duplicates from Sorted Array

LeetCode——Remove Duplicates from Sorted Array

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.

思路:很笨

記不太清自己的思路了。

class Solution {

public int removeDuplicates(int[] nums) {

int global = 0 ;

int j = 0;

for(int i = 0;i < nums.length;){

if(nums.length == 0){

return 0;

}

else if(nums.length == 1){

nums[0] = nums[0];

return 1;

}

else{

if((i+1)<nums.length&&nums[i] == nums[i+1]){

j = i + 1;

int count = 0;

while(j<nums.length&&nums[i] == nums[j]){

count ++;

j ++;

}

nums[global++] = nums[i + count];

i = j;

}

else{

nums [global++] = nums[i];

i++;

}

}

}

return global;

}

}

後記

把後面的一道題做了之後思路清晰了很多

用兩個指標,i和j,i是慢的,j是快的

兩兩比較,但是需要注意的就是兩兩比較下來能確定的只有一個。所以,需要對陣列的首個元素或者是末尾元素做一個判斷。

我是將兩兩比較的元素的後面一個元素作確定,所以最開始需要對陣列的首個元素做判斷。

虛擬碼:

當陣列為空時,則直接返回0;

當陣列的長度為1時,直接返回1;

當陣列長度大於1時,這種情況下,新的陣列至少長度大於1,即至少有一個元素。於是,首先將陣列的收割元素確定為新陣列的首個元素。對第二個及之後的元素進行判斷。nums[j]和nums[j+1](j的初始值為0,因為兩兩比較確定第二個的值,也就是確定從索引為大於等於1的值)的值作比較,如果相等,則直接跳過;如果不相等,則將後面的那個值nums[j]賦給nums[i],同時新陣列的長度i增加1。

class Solution {

public int removeDuplicates(int[] nums) {

int i = 1;

if(nums.length==0){

return 0;

}

else if(nums.length == 1){

return 1;

}

else{

nums[0]= nums[0];

for(int j =0;j<nums.length-1;j++){

if(nums[j]!=nums[j+1]){

nums[i] = nums[j+1];

i++;

}

}

}

return i;

}

}

leetcode網站上給出的solution

思路:也是採用了兩個計數器,i和j,i為慢的,j為快的

但是我沒有想到的就是,因為慢的一定會比快的慢,而且是已經確定下來了的,所以可以直接把快的和慢的表示的元素直接比較。這樣很節省。

要注意的是,慢的表示的是陣列的所以,最後輸出的陣列長度時,需要對它加1。

class Solution{

public int removeDuplicates(int nums[]){

if(nums.length == 0){

return 0;

}

int i =0;

for(int j = 1;j<nums.length;j++){

if(nums[j]!=nums[i]){

i++;

nums[i] = nums[j];

}

}

return i+1;

}

}