美文网首页
Remove Duplicates from Sorted Ar

Remove Duplicates from Sorted Ar

作者: 无为无悔 | 来源:发表于2016-09-06 20:59 被阅读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)

    相关文章

      网友评论

          本文标题:Remove Duplicates from Sorted Ar

          本文链接:https://www.haomeiwen.com/subject/xtadettx.html