LeetCode(28)-Remove Duplicates from Sorted Array
2024-08-29 14:54:24
题目:
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.
思路
- 题意是把有序数组的重复元素去掉,返回不重复元素的个数n,至于后面的元素怎么排列没有要求,前n个必须是不重复的元素,相对顺序不变
- 设置两个变量,一个用来存放最后一个不重复数的坐标,一个用来往下比较看是不是初夏重复
-
代码
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null){
return 0;
}
if(nums.length == 1){
return 1;
}
int n = nums.length;
int j = 0;
for(int i = 0; i < (n-1);i++){
if(nums[i] != nums[i+1]){
nums[j++] = nums[i];
}
if(i == (n-2)){
nums[j] = nums[n-1];
}
}
return (j+1);
}
}
最新文章
- WPF整理-XAML构建后台类对象
- SQLServer中给表增加组合唯一约束
- window对象的inner/outer/page/screen详解
- HDU-1394 Minimum Inversion Number 线段树+逆序对
- laravel下使用阿里云oss上传图片
- .NET技术+25台服务器怎样支撑世界第54大网站(转)
- [mock]8月8日
- Android 仿PhotoShop调色板应用(三) 主体界面绘制
- css设置
- linux文件特殊属性介绍(s,s,t)
- python学习基础总结
- 【转载】C++中替代sprintf的std::ostringstream输出流详解
- MapReduce -- TF-IDF
- java-Spring 管理bean例子
- MySQL升级后1728错误解决方案
- ubuntu &#39;yuan&#39; update
- 微信小程序——节奏练耳 宣传页
- YUM常用命令详解
- JBDC—③数据库连接池的介绍、使用和配置
- fatal error: sys/cdefs.h: No such file or directory
热门文章
- 3.关于QT中的MainWindow窗口,MenuBar,ToolBar,QuickTip等方面的知识点
- FFmpeg的H.264解码器源代码简单分析:解码器主干部分
- C++中struct类型增强
- Android中JNI编程详解
- SSH深度历险(八) 剖析SSH核心原理+Spring依赖注入的三种方式
- iOS中 动态启动图GIF的简单设置 韩俊强的博客
- VS2010创建和调用动态链接库
- ASP.NET实现网页版小优盘
- 海量数据挖掘MMDS week4: 推荐系统之隐语义模型latent semantic analysis
- 【linux】mkfifo 命令创建命名管道实现进程之间通信