Java [leetcode 26]Remove Duplicates from Sorted Array
2024-08-22 00:01:45
题目描述:
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.
解题思路:
对组遍历一次,并且设置一个计数器,当数组前后的元素不一样时计数器加一,同时将不一样的数字放到对应计数器的位置处。
代码如下:
public int removeDuplicates(int[] nums) {
int length = nums.length;
int count = 1;
if (length == 0)
return 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i - 1] == nums[i])
continue;
else {
nums[count] = nums[i];
count++;
}
}
return count;
}
最新文章
- C++随笔:.NET CoreCLR之GC探索(4)
- Java Spring的IoC和AOP的知识点速记
- OData的初步认识
- 装配bean
- js基本类型 引用类型
- win10开始菜单打不开怎么办 win菜单键没反应解决办法
- cas4.2.7实现单点登录
- SPFA【模板】单源最短路径
- Factom(公证通)--基于区块链的存证系统
- mysql在win10下的卸载
- OpenCV中feature2D——BFMatcher和FlannBasedMatcher
- 小程序2-基本架构讲解(一)JSON配置与详解
- 4-24日 collections模块 random模块 time模块 sys模块 os模块
- 【转】oracle中的游标的原理和使用详解
- js中引号(";";)中间设置变量
- 1: 介绍Prism5.0 Introduction to the Prism Library 5.0 for WPF(英汉对照版)
- 2018 Multi-University Training Contest 1 Distinct Values 【贪心 + set】
- Zabbix——使用邮件报警
- 怎样将游戏从Unity导到iOS设备上
- WPF之ContextMenu的命定绑定