Remove Duplicates from Sorted Array

  • 描述

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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容