码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted Array

时间:2018-03-20 21:41:44      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:color   cat   href   mod   https   ace   length   must   sorted   

问题

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 by modifying the input array in-place with O(1) extra memory.

代码

    public int removeDuplicates(int[] nums) 
    {
        int i = 0;
        for(int n : nums)
        {
            if(i==0||n>nums[i-1])
                nums[i++] = n;
        }
        return i;
    }

因为是有序的数组所以可以通过foreach循环直接进行比较。

Remove Duplicates from Sorted Array

标签:color   cat   href   mod   https   ace   length   must   sorted   

原文地址:https://www.cnblogs.com/mymym/p/8612495.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!