[leetcode][array]remove dulplicates from sorted array
来源:互联网 发布:vb.net 开发手机页面 编辑:程序博客网 时间:2024/05/29 19:14
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 A = [1,1,2]
,
Your function should return length = 2
, and A is now [1,2]
.
solution:
①需要返回重构的A的长度②检验返回长度内,A是否已经没有重复(长度外数据不考虑)
·条件②表明,我们不用考虑长度外的数据,只需要保证长度内的数据无重复且sorted(有序)即可,因此长度内的数据遇到重复时可以使用长度外的不重复数据进行覆盖。
·两个参数,一个i用来从前向后循环数组,一个index(从0开始)用来记录最后一个没有重复的数字的位置。当index位置后面出现不重复的数字,将index值加一并附新的不重复值,当index后面全部重复出现,则index+1就是不重复数组长度。
·考虑空集和只有一个元素的数组(可以整合进去)
code:
<span style="color:#333333;">public class Solution { public int removeDuplicates(int[] A) { int index = 0;int length = A.length;if (</span><span style="color:#ff0000;">length == 0</span><span style="color:#333333;">) {return 0;}else {for (int i = 1; i < length; i++) {if (A[i] == A[index]) {</span><span style="color:#ff0000;">continue;</span><span style="color:#333333;">}else {</span><span style="color:#ff0000;">index++;A[index] = A[i];//直接覆盖</span><span style="color:#333333;">}}return index+1;} }}</span>
0 0
- [leetcode][array]remove dulplicates from sorted array
- [leetcode][array] Remove Duplicates from Sorted Array
- 【Leetcode】【Array】Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- leetcode 35: Remove Duplicates from Sorted Array
- [LeetCode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array
- Leetcode: Remove Duplicates from Sorted Array
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array
- js操作table排序
- 读书笔记--Linux监控与调优(2)--性能分析工具
- 在Vivado HLS中综合时如何指定端口的综合类型
- C++第二次复习
- sprintf和printf
- [leetcode][array]remove dulplicates from sorted array
- C语言实现捞鱼问题
- 《UNIX环境高级编程》笔记:第2章 UNIX标准及实现
- [BestCoder] Round #2
- js中argument argument
- 1.1 什么是OpenGL
- Perl 子程序变量外部使用--又称为闭包
- drop tablespace TEST including contents and datafiles;
- 《UNIX环境高级编程》笔记:第3章 文件I/O