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

[leedcode 26] Remove Duplicates from Sorted Array

时间:2015-07-08 22:25:13      阅读:137      评论:0      收藏: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 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.

public class Solution {
    //本题有个要求:需要原地进行处理,即不能占用额外空间。因此考虑声明一个指针,指针前面的值都是非重复的
    //然后遍历一遍数组,每个值与其前一个值进行比较,若相同,则前进索引,若不同,则将此值放入数组前面
    //以下是一种解法,次解法的缺点是,当出现不重复的数组时,nums[start++]=nums[index++]扔会运行
    //本题需要注意,start的初始值
    
    public int removeDuplicates(int[] nums) {
       if(nums.length==0) return 0;
        int start=1;
       int index=1;
        while(index<nums.length){
           if(nums[index]==nums[index-1]){
               index++;
           }else{
               nums[start++]=nums[index++];
               
           }
       }
       return start;
            
    }
    
}

 

[leedcode 26] Remove Duplicates from Sorted Array

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4631339.html

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