Remove Duplicates from Sorted Array
2016-07-05 06:31
316 查看
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.
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null ) return 0;
if(nums.length <=1) return nums.length;
int current = 1;
for(int i=1; i<nums.length; i++) {
if(nums[i]!=nums[i-1]){
nums[current++] = nums[i];
}
}
return current;
}
}
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.
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null ) return 0;
if(nums.length <=1) return nums.length;
int current = 1;
for(int i=1; i<nums.length; i++) {
if(nums[i]!=nums[i-1]){
nums[current++] = nums[i];
}
}
return current;
}
}
相关文章推荐
- 源码推荐(0705):简仿映客直播App,UITableView右侧索引
- 这几天已经连续轰炸一个开锁的人电话短信无数次
- JavaScript事件使用指南
- Maximum Product of word lengths
- Generalized Abbreviation
- Search Range in Binary Search Tree
- Serialize and Deserialize Binary Tree
- Create Maximum Number
- Struts2系列:(28) i18n-6 localized text参数化
- Palindrome Permutation
- 也谈前端面试常见问题之『数组乱序』
- geeksforgeeks@ Minimum sum partition (Dynamic Programming)
- win10系统每天凌晨3点左右,自动关机重启
- Java股票数据下载
- Python股票历史数据下载
- Struts2系列:(27)i18n-5 i18n tag
- Combination Sum | & || & ||| & IV
- 安卓学习笔记(四)Button监听
- 关于网络的七层协议及相关信息记忆图
- 安卓学习笔记(五)TextView实现跑马灯(自建类,可多个文本同时实现)