您的位置:首页 > 其它

Remove Duplicates from Sorted Array

2015-10-05 20:22 399 查看
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].

从排序的数组中删除重复的元素

算法思路:设置两个指针i和j,初始化i=0;j=1,i用来指向需要被覆盖的数字的前一个元素下标,j用来遍历数组,比较i和j指向的值,如果不相等,i++并将j指向的值覆盖此时i指向的值,如果i和j指向的值相等,则继续向后遍历。

例如 1 1 2

i j

(1)比较i和j指向的值,i和j的值相等,所以j++向后遍历,j指向2

(2)比较i和j指向的值,值不相等,所以先让i增1,然后将j指向的值放到i的位置,数组变为1 2 2

public class RemoveDuplicatesFromSortedArray {

public static void main(String[] args) {
int[] array={1,1,2,2,3};

int result=remove(array);
System.out.println(result);
}

public static int remove(int[] array)
{
if(array!=null)
{
int i=0;
for(int j=1;j<array.length;j++)
{
if(array[j]!=array[i])
{
i++;
array[i]=array[j];
}
}
return i+1;
}else
return -1;
}

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