Remove Duplicates from Sorted Array
2015-07-02 15:54
351 查看
描述
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表示数组的位置。
如果j指向的数组与i指向的数据重复,则j移动到下一个位置。
如果指向的值不重复,则将i+1,数据移动到i+1,j继续增加。
Runtime: 32 ms
注意
1.首先要判断这个数组是否为空,如果为空的话,情况特殊。
注意对边界情况要考虑清楚。
2.另外多定义了一个数据k,多占用了一个空间,可以省略这个k,用j当做循环就可以了。可以做一些改进。
c语言版本
Runtime: 16 ms
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表示数组的位置。
如果j指向的数组与i指向的数据重复,则j移动到下一个位置。
如果指向的值不重复,则将i+1,数据移动到i+1,j继续增加。
class Solution { public: int removeDuplicates(vector<int>& nums) { int n=nums.size(); int i,j,k; if(n==0) return 0; i=0;j=1; for(k=1;k<n;++k) { if(nums[i]!=nums[j]) { i++; nums[i]=nums[j]; j++; } else j++; } return i+1; } };
Runtime: 32 ms
注意
1.首先要判断这个数组是否为空,如果为空的话,情况特殊。
注意对边界情况要考虑清楚。
2.另外多定义了一个数据k,多占用了一个空间,可以省略这个k,用j当做循环就可以了。可以做一些改进。
c语言版本
int removeDuplicates(int* nums, int numsSize) { if(numsSize==0) return 0; int i,j; i=0; for(j=1;j<numsSize;++j) {if(nums[i]!=nums[j]) nums[++i]=nums[j]; } return i+1; }
Runtime: 16 ms
相关文章推荐
- SQL Server 服务开启、关闭等 及数据类型
- iOS开发学习网站汇总
- StretchAnimation伸缩动画.
- CSS3 禁用文本复制的属性:user-select
- CSS3 禁用文本复制的属性:user-select
- QString & String
- Cocos-js——粒子系统
- ssh 免密码登录配置
- 论文提要“Selective Search for Object Recognition”
- 基于FT5x06嵌入式Linux电容触摸屏驱动
- SimpleDateFormat 源码解析
- 无刷新上传
- hadoop之伪分布式
- Linux下SSH安全控制登录
- Jmeter 1 - 打开Badboy录制的脚本报错 ‘only whitespace content allowed before start tag and not\ufffd’
- 创建Windows10 密码重设盘
- 求二叉树的深度和宽度[Java]
- ubuntu启动过程
- android4.0触摸屏(touchscreen)以及屏幕按键驱动解析
- “The connection to adb is down, and a severe error has occured”的解决方法汇总