您的位置:首页 > 其它

LeetCode之Remove Duplicates from Sorted Array

2015-06-17 20:46 357 查看
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.

本质就是在原有数组中把重复的数放到后面。

基本思路就是把重复的和不重复的交换,让重复的一直往后走,最后不重复的都放在前面。但是交换有点太浪费时间,所以改成复制。

所以需要维护两个指针(一个放当前最后一个不重复的数c,一个一直往前走m),和一个value值(放当前最后一个不重复的值,可以和第一个指针合并)。

public int removeDuplicates(int[] nums) {
if(nums.length == 0)    return 0;
int length = 0;
int v = 0, m = 0, c = 0;
v = nums[0];
while(m < nums.length){
if(nums[m] == v)    m++;
else{
c++;
nums[c] = nums[m];
v = nums[m];
}
}
length = c + 1;
return length;
}


基本上就是这样了,Java 跑好慢。。。

161 / 161 test cases passed.

Status: Accepted

Runtime: 428 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode