remove duplicates from sorted Array
2015-12-29 21:52
267 查看
Given: a sorted array,
to do: remove the duplicates in place such that each element appear only once
and return the new length
requirment: do not allocate extra space for another array, you must do this in
place with constant memory.
e.g. input array nums=[1,1,2]
output length = 2, with the first two elements of nums being 1 and 2
respectively. it doesn't matter what you leave beyond the new length.
26. Remove Duplicates from Sorted Array
Java code:
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums==null||nums.length==0)return 0;
int index = 0;
int i;
for (i=1; i<nums.length; i++)
{
if(nums[index]!=nums[i]){
nums[++index]=nums[i];
}
}
return index+1;
}
}
another solution
public class Solution{
public int removeDuplicates(int[] nums){
if(nums==null || nums.length==0)
return 0;
Integer cur = null;//special value, means uninitialized.
int len = 0;
for(int n : nums){
if(cur == null || cur < n){
cur = n;
nums[len++] = n;
}
}
return len;
}
}
to do: remove the duplicates in place such that each element appear only once
and return the new length
requirment: do not allocate extra space for another array, you must do this in
place with constant memory.
e.g. input array nums=[1,1,2]
output length = 2, with the first two elements of nums being 1 and 2
respectively. it doesn't matter what you leave beyond the new length.
26. Remove Duplicates from Sorted Array
Java code:
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums==null||nums.length==0)return 0;
int index = 0;
int i;
for (i=1; i<nums.length; i++)
{
if(nums[index]!=nums[i]){
nums[++index]=nums[i];
}
}
return index+1;
}
}
another solution
public class Solution{
public int removeDuplicates(int[] nums){
if(nums==null || nums.length==0)
return 0;
Integer cur = null;//special value, means uninitialized.
int len = 0;
for(int n : nums){
if(cur == null || cur < n){
cur = n;
nums[len++] = n;
}
}
return len;
}
}
相关文章推荐
- 实战c++中的智能指针unique_ptr系列--通过unique_ptr对shared_ptr进行初始化
- 实战c++中的智能指针unique_ptr系列--通过unique_ptr对shared_ptr进行初始化
- 2015/12/29 eclipse 设置要点 空间 项目 类 eclipse汉化
- Git 学习(1)
- excel 2010 如何设置日期选择器
- 学习网站
- 字符串16进制转int
- nyoj 949哈利波特(细节题)
- Java语言程序设计-总结
- 广点通 (iOS完整版)
- 用SAE搭建一个微信公众号
- 线程与进程的区别、联系
- 用CasperJs自己主动浏览页面
- 关于索引
- 在Linux系统中安装JDK
- Java回调
- 第一次作业
- see 二分 again
- 利用静态链表作集合运算(A-B)U(B-A)
- android 的颜色对比表