remove duplicate from sorted list(keep only 1 per 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].

比較簡單的一個題, 時間O(n), 空間O(1)

public class Solution {
    public int removeDuplicates(int[] A) {
        // use two pointers
        int len = A.length;
        
        int p = 0, q = 0;
        // p at where to be replaced and q at the scanning position
        
        while( q < len){
            int tmp = A[q];
            while(q < len && A[q] == tmp)   q++;
            A[p++] = tmp;
        }
        
        
        
        return p;
        
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章