leetcode:Remove Duplicates from Sorted Array 【Java】
2016-03-05 21:27
507 查看
一、问题描述
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.
二、问题分析
使用两个索引。
三、算法代码
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
1and
2respectively.
It doesn't matter what you leave beyond the new length.
二、问题分析
使用两个索引。
三、算法代码
public class Solution { public int removeDuplicates(int[] nums) { if(nums.length == 0){ return 0; } int cur = 0; for(int index = 1; index <= nums. length - 1; index++){ if(nums[cur] != nums[index]){ nums[++cur] = nums[index]; } } return cur + 1; } }
相关文章推荐
- 【Java】ArrayList集合容器
- Java BigInteger的简单使用
- 【JAVA】29、面向对象的基本概念和三个特征
- 【Java】无条件分支跳转
- java数组的使用
- 【转】java字符串和byte数组间转换
- 【Java】]Java的三大控制结构
- leetcode:Jump Game 【Java】
- 2016.3.5 第一次Java实验
- LeetCode : Integer to Roman [java]
- Adam学习1之环境搭建(含window下eclipse配置)
- java 值传递与地址传递(引用)的区别
- Struts中ActionContext和ServletActionContext的比较
- Eclipse上安装GIT插件EGit及使用
- SpringMVC视图解析器
- java动态生成验证码图片
- Java之变上三角矩阵
- Eclipse背景颜色设置(设置成豆沙绿色保护眼睛,码农保护色)
- LeetCode : Container With Most Water [java]
- 循环次数不确定要终止循环的方式