您的位置:首页 > 编程语言 > Java开发

leetcode-26. Remove Duplicates from Sorted Array

2016-11-22 10:32 369 查看

leetcode-26. Remove Duplicates from Sorted Array

题目:

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.

基本思路就是记录一下当前记录的值,当前的位置和当前位移的距离这三个量然后逐点的变化,直至pos+dis

public class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null || nums.length < 1){
return 0;
}
if(nums.length==1) return nums[0];
int cur = nums[0];
int pos = 1;
int dis = 0;
while(pos+dis<nums.length){
nums[pos] = nums[pos+dis];
if(nums[pos]!=cur){
cur = nums[pos++];
}else{
dis++;
}
}
return pos;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java