LeetCode 127 Remove Duplicates from Sorted Array

来源:互联网 发布:js 自定义日期选择器 编辑:程序博客网 时间:2024/06/05 19:58
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].

分析:

两个指针,i顺序往后遍历,j指向有效新数组尾。

public class Solution {    public int removeDuplicates(int[] A) {        if(A.length < 2) return A.length;        int i=1;        int j=0;        while(i<A.length){            if(A[i] == A[j])                i++;            else{                j++;                A[j] = A[i];                i++;            }        }        A = Arrays.copyOf(A, j+1);        return A.length;    }}


0 0