Remove Duplicates from Sorted Ar

2016-09-06  本文已影响0人  无为无悔

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

solution:

public class Solution {

    public int remove(int[] arr) {
        if(arr == null || arr.length == 0)
            return 0;
        if (arr.length == 1)
            return 1;

        int idx = 0;
        for(int i=1; i < arr.length; ++i) {
            if(arr[idx] != arr[i]) {
                arr[++idx] = arr[i];  # 注意‘++’的位置
            }
        }
        return (idx + 1);
    }
}

时间复杂度O(N),空间复杂度O(1)

上一篇下一篇

猜你喜欢

热点阅读