Remove Duplicates from Sorted Array II
2015-07-02 16:34
295 查看
描述
Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice?
For example, Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3]
中文
让排好序的数组最多重复两次。
分析:和上题一样,只要间距相差2就可以了。
不过还是要注意一些。
k表示循环
i表示新排列的数组下标
j表示旧排列的数组下标
Runtime: 20 ms
c语言版本
Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice?
For example, Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3]
中文
让排好序的数组最多重复两次。
分析:和上题一样,只要间距相差2就可以了。
不过还是要注意一些。
k表示循环
i表示新排列的数组下标
j表示旧排列的数组下标
class Solution { public: int removeDuplicates(vector<int>& nums) { int n=nums.size(); int i,j,k; if(n==0) return 0; if(n<=2) return n; i=1;j=2; for(k=2;k<n;++k) { if(nums[i-1]!=nums[j]) { ++i; nums[i]=nums[j]; ++j; } else ++j; } return i+1; } };
Runtime: 20 ms
c语言版本
int removeDuplicates(int* nums, int numsSize) { if(numsSize==0) return 0; if(numsSize<2) return numsSize; int i,j,k; i=1;j=2; for(k=2;k<numsSize;++k) { if(nums[i-1]!=nums[j]) { ++i; nums[i]=nums[j]; ++j; } else ++j; } return i+1; }Runtime: 8 ms
相关文章推荐
- 实现两列等高
- Linux.CommanlineTool.grep
- Swift开发学习(二):Playground
- Shell脚本编写
- redis 集群
- Android 开源框架Universal-Image-Loader完全解析(三)---源代码解读
- TK8.4 PaneWindow 组件
- Storm简述及集群安装
- 把源文件夹中的文件名称写入目的文件夹指定后缀的各个文件中
- Git使用笔记
- 正则
- 判断复选框是否被选中
- .Net学习笔记----2015-07-02(选择文件对话框、保存对话框、字体和颜色对话框)
- vim2
- 用Redis实现微博关注关系
- SPDIF S24_LE S24_3LE调试小结
- Android 开源框架Universal-Image-Loader完全解析(二)--- 图片缓存策略详解
- CentOS 修改主机名
- opencv访问图像像素
- meta标签 -- 移动端