您的位置:首页 > 其它

leetcode--Remove Duplicates from Sorted Array

2017-08-08 09:04 337 查看
Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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 ofnums being 
1
 and 
2
 respectively. It doesn't matter what you leave beyond the new length.

题意:给定一个排序数组,移除重复元素,返回新数组的长度。

分类:数组,双指针

解法1:双指针,一个用于遍历,一个用于指向当前覆盖位置。

[java] view
plain copy

public class Solution {  

    public int removeDuplicates(int[] nums) {  

        if(nums.length==0) return 0;  

        int pre = nums[0];  

        int count = 1;  

        for(int i=1;i<nums.length;i++){  

            if(pre!=nums[i]){                 

                pre = nums[i];  

                nums[count] = nums[i];  

                count++;  

            }  

        }  

        return count;  

    }  

}  

原文链接http://blog.csdn.net/crazy__chen/article/details/45584177
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: