码迷,mamicode.com
首页 > 编程语言 > 详细

Remove Duplicates From Sorted Array leetcode java

时间:2015-12-16 15:21:00      阅读:168      评论: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.

算法分析:一个有序数组,出去其中出现次数大于1的数,返回剩余元素个数

代码:设置两个指针,i 遍历原数组,是去除重复后的下标

public int removeDuplicates(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
        int len = nums.length;
        int j = 1; //数组第一个元素是不需要变的,所以长度至少为1
        for(int i = 1; i < len; i++){ //数组遍历从下标1开始
            if(nums[i] == nums[i - 1])
                continue;
            else {
                nums[j++] = nums[i];
            }
        }
        
        return j;
    }

 

Remove Duplicates From Sorted Array leetcode java

标签:

原文地址:http://www.cnblogs.com/mydesky2012/p/5051127.html

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