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

26.Remove Deplicates from Sorted Array

时间:2017-07-25 01:01:46      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:div   another   ext   ==   elements   his   function   ret   mem   

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 nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn‘t matter what you leave beyond the new length.

算法:

因为数组已经有序,我们可以维持两个指针i 和 j, 只要nums[i] == nums[j], 就增加j 来跳出循环。

当遇到nums[j] != nums[i], 查重循环结束, 我们必须把nums[j] 的值复制给nums[i+1】,i 然后增加。

重复这一过程直到j 到达数组尾部。

public int removeDuplicates(int[] nums) {
    if (nums.length == 0) return 0;
    int i = 0;
    for (int j = 1; j < nums.length; j++) {
        if (nums[j] != nums[i]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
}

  

26.Remove Deplicates from Sorted Array

标签:div   another   ext   ==   elements   his   function   ret   mem   

原文地址:http://www.cnblogs.com/dreamafar/p/7231782.html

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