您的位置:首页 > 其它

LeetCode Remove Duplicates from Sorted Array

2014-11-03 20:00 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 A = 
[1,1,2]
,

Your function should return length = 
2
, and A is now 
[1,2]
.

题意:从排序的数组中删除重复的元素,使得每个元素只出现一次,返回新的数组的长度

思路:将新的数组的索引cnt=0,将数组的第一个元素赋值,即a[cnt] = a[0],然后从1到len遍历数组,如果a[i] == a[cnt - 1]继续

public class Solution {
public int removeDuplicates(int[] A) {
if (A.length == 0) return 0;
int cnt = 0;
A[cnt++] = A[0];
for (int i = 1, len = A.length; i < len; i++) {
if (A[i] == A[cnt - 1]) continue;
else A[cnt++] = A[i];
}

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