Remove Duplicates from Sorted Array
来源:互联网 发布:java编程思想视频全集 编辑:程序博客网 时间:2024/06/06 02:49
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 = [1,1,2]
,
Your function should return 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.
需要注意几点:
1.输入的是已排序的数组;
2.不可再申请额外空间;
3.数组中元素的位置不能改变。比如对于数组[1,1,1,4,5],移除重复元素后为[1,4,5],起始数字为1,而不能是其它数字。
package leetcode;
public class RemoveDuplicatesFromSortedArray {
public staticint removeDuplicates(int[] nums) {
int ans = nums.length;
if (ans == 0 ||ans == 1) return ans;
int index = 1;
for (int i = 1; i<nums.length;i++){
if (nums[i] ==nums[i-1]){
continue;
}else{
nums[index] =nums[i];
index++;
}
}
return index;
}
public staticvoid main(String[] args) {
// TODO Auto-generated method stub
int[] nums = {1,1,2};
System.out.println(removeDuplicates(nums));
}
}
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates From Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- C++11:override 与 final
- HDU ACM 4502 吉哥系列故事——临时工计划 ->动态规划
- iOS开发UI高级—12ios应用数据存储方式(偏好设置)
- androidstudio 优化gradle编译效率
- 黑马程序员--java 单例设计模式
- Remove Duplicates from Sorted Array
- Spring与Quartz结合
- iOS开发UI高级—13ios应用数据存储方式(归档)
- Leetcode Note: Linked List Easy Section Part 1
- UML简单介绍(十四)——类图的基本概念与组件介绍
- 编译安装Qt4(二)
- 多渠道打包实现
- NSUserDefaults性能优化问题
- opencv基础函数代码