Related Topics:[Array][Two Pointers]
Similar Questions:[Remove Element]
題目: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 A = [1,1,2]
,
Your function should return length = 2
, and A is now [1,2]
.
思路
這道題要我們從有序數組中去除重復項,和之前那道[ Remove Duplicates from Sorted List 移除有序鏈表中的重復項] 的題很類似,但是要簡單一些,因為畢竟數組的值可以通過下標直接訪問,而鏈表不行。
我們使用快慢兩個指針來記錄遍歷的坐標,快指針指向每一個數組元素,慢指針指向目前對比的項。最開始時兩個指針都指向第一個數字,如果兩個指針指的數字相同,則快指針向前走一步,如果不同,則兩個指針都向前走一步,這樣當快指針走完整個數組后,慢指針當前的坐標加1就是數組中不同數字的個數。
java解法:
class Solution {
public int removeDuplicates(int[] nums) {
int idx=0;
for(int i=1;i<nums.length;i++) {
if(nums[i]!=nums[idx]) {
idx++;
nums[idx]=nums[i];
}
}
return idx+1;
}
}