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
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; } }
相关文章推荐
- numpy 安装错误
- [C++] Variable/Hex conversion
- 浅谈C++多态性
- 归一化方法总结
- 黑马程序员—OC语言小知识点及示例
- 数组连续子数组的和最大
- 浅谈C++多态性
- 操作系统之处理机管理
- HLG 1039 修路 二分
- 【static&extern】c语言static用法
- velocity自定义动画
- 病毒侵袭持续中---hdu3065(AC自动机模板)
- 【PAT】1003. Emergency (25)
- C++学习–应用篇(Windows/Linux)(书籍推荐及分享)
- 项目成本管理总结
- QT5 学习之路22---事件过滤器
- Matlab-vision包学习-Object Detection and Recognition-标记正例
- GOF 23 设计模式之 备忘录模式(Memento)
- Part 4 using entity framework
- Android基础学习之Preference(配置存储)