26. Remove Duplicates from Sorted Array
2016-04-19 17:12
246 查看
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 nums =
Your function should return length =
It doesn't matter what you leave beyond the new length.
思路:用count记录相同的个数。对于nums[i]到它相同的有多少个,那么他实际的位置就应该是nums[i-count];\
代码如下(已通过leetcode)
public class Solution {
public int removeDuplicates(int[] nums) {
int length=nums.length;
int n=0;
for(int i=0;i<length-1;i++) {
if(nums[i]==nums[i+1]) n++;
nums[i-n+1]=nums[i+1];
}
return length-n;
}
}
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums =
[1,1,2],
Your function should return length =
2, with the first two elements of nums being
1and
2respectively.
It doesn't matter what you leave beyond the new length.
思路:用count记录相同的个数。对于nums[i]到它相同的有多少个,那么他实际的位置就应该是nums[i-count];\
代码如下(已通过leetcode)
public class Solution {
public int removeDuplicates(int[] nums) {
int length=nums.length;
int n=0;
for(int i=0;i<length-1;i++) {
if(nums[i]==nums[i+1]) n++;
nums[i-n+1]=nums[i+1];
}
return length-n;
}
}
相关文章推荐
- EventBus使用详解(二)——EventBus使用进阶
- andfix增量升级更新
- 绕任意轴旋转的矩阵推导
- poj 1258 Agri-Net
- java基本数据类型传递与引用传递区别详解
- shadow$_monitor_和shadow$_klass_
- UITabBarController
- KMP算法——从入门到懵逼到了解
- 布局填充器(LayoutInflater)
- Java 线程第三版 第四章 Thread Notification 读书笔记
- 1-6 01:与指定数字相同的数的个数
- Canvas中保存画布状态及还原
- 影响vector效率的关键
- 凹凸按钮样式
- QWT的安装与配置
- Struts2 Could not find action or result:错误
- windows下安装多个mysql
- JavaMail技术 用java代码发送邮件
- Linux修改文件属性和权限
- 异步加载图片-SDWebImage