問題:
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.
大意:
給出一個有序數(shù)組,移除重復的數(shù)字,讓每個元素只出現(xiàn)一次,并返回新的長度。
不要分配額外的空間給另一個數(shù)組,你必須在固定的內(nèi)存下去做。
舉例:
給出輸入的數(shù)組為 nums = [1,1,2],
你的函數(shù)應該返回長度 = 2,并讓前面兩個數(shù)字為單獨的1和2。在新長度之外的位置無所謂你留下了什么內(nèi)容。
思路:
這道題和LeetCode筆記:27. Remove Element這個很類似,只不過這道題的難度在于,在操作中不能隨意改變數(shù)組中原本元素的位置,因為你要保持它后面的數(shù)字還是有序的,才好去比較相鄰的數(shù)字是否一樣。其實也簡單,我們弄一個變量記錄上一個單獨的數(shù)字,再弄一個變量記錄該數(shù)字后面的位置序號,往后遍歷,直到遇到不一樣的數(shù)字,才把那個數(shù)字放到該位置序號來,然后把記錄單獨數(shù)字的變量設(shè)為這個新數(shù)字,記錄位置的變量序號+1,繼續(xù)往后遍歷,因為是隨著遍歷過程往前放數(shù)字,所以不會影響到后面的數(shù)字順序。
代碼(Java):
public class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int position = 1;
int lastNumber = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > lastNumber) {
nums[position] = nums[i];
position++;
lastNumber = nums[i];
}
}
return position;
}
}
合集:https://github.com/Cloudox/LeetCode-Record