Leetcode——remove-element
2016-07-14 14:55
381 查看
remove-duplicates-from-sorted-array
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].
remove-element
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
今天在Leetcode上看到的两道题,解法比较相似。现整理如下:
remove-duplicates-from-sorted-array(删除排序数组的重复元素)
remove-element(删除数组中的给定元素)
思路:动态维护一个值index。
比如题一:一次遍历整个数组元素,当元素值发生变化时,更新index。输出为新的数组长度。
注意两题有一点不同的是输出。题一只保留重复元素的一次,题二是删除指定元素。
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].
remove-element
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
今天在Leetcode上看到的两道题,解法比较相似。现整理如下:
remove-duplicates-from-sorted-array(删除排序数组的重复元素)
remove-element(删除数组中的给定元素)
思路:动态维护一个值index。
比如题一:一次遍历整个数组元素,当元素值发生变化时,更新index。输出为新的数组长度。
int removeDuplicates(int A[], int n) { if(A==NULL||n<=0) return 0; int newn=0; int i=0; while(i<n) { if(A[newn]!=A[i]) { newn++; A[newn]=A[i]; } i++; } return newn+1; }
注意两题有一点不同的是输出。题一只保留重复元素的一次,题二是删除指定元素。
int removeElement(int A[], int n, int elem) { int index=0; int i=0; while(i<n) { if(A[i]!=elem) { A[index++]=A[i]; } i++; } return index; }
相关文章推荐
- 带色彩恢复的多尺度视网膜增强算法(MSRCR)的原理、实现及应用。
- Docker remote API简单配置使用
- Prism6下的MEF:第一个Hello World
- async和await
- ASCII,gb2312,GBK,UTF-8的区别
- git与svn的区别
- OpenCV Mat数据类型及位数总结
- Java 构造函数的详解
- wpf内存泄漏问题
- Vigenère 密码题解
- easyui combobox
- 使用源码编译安装nginx
- dd 与cp的区别
- MogoDB在线教程
- PAT (天梯)L2-004. 这是二叉搜索树吗?
- Linux下mysql数据库的命令
- 16.7.14 B 组总结
- java.util.concurrent源码学习一
- 安卓软键盘的关闭
- 读书摘要——第四章