LeetCode – Remove Duplicates from Sorted Array (Java)

来源:互联网 发布:mysql数据库的优点 编辑:程序博客网 时间:2024/06/11 04:43

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].

Thoughts

The problem is pretty straightforward. It returns the length of array with unique elements, but the original array need to be changed also. This problem should be reviewed with Remove Duplicates from Sorted Array II.

Java Solution

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


0 0