LeetCode Remove Duplicates from Sorted Array
来源:互联网 发布:linux 返回上级目录 编辑:程序博客网 时间:2024/05/19 04:56
问题网址:https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
问题描述:
给定一个有序数组,删除重复内容,使每个元素只出现一次,并返回新的长度。
不要为其他数组分配额外的空间,您必须通过在O(1)额外的内存中就地修改输入数组来实现这一点。
问题例子:
Given 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.
这个问题没什么难度
两指针方法
由于数组已经排序,我们可以保留两个指针i和j,其中i是慢跑者,而j是快跑者。 只要nums [i] = nums [j] ,我们增加j跳过重复。
当我们遇到nums [j]≠nums [i]时,重复运行已经结束,因此我们必须将其值复制到nums [i + 1] 。 i然后递增,我们再次重复相同的过程,直到j到达数组的末尾。
public int removeDuplicates(int[] nums) { if (nums.length == 0) return 0; int i = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1;}
复杂性分析
时间复杂度:O(n)。 假设n是数组的长度。 i和j中的每一个最多跨越n个步骤。
空间复杂度:O(1)。
阅读全文
0 0
- [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
- [leetcode]Remove Duplicates from Sorted Array II
- JS设计模式-单例模式
- Java中的除法结果与除数被除数的类型有关
- ES6 函数的拓展
- 祝大家双旦快乐——点开有彩蛋哦
- 【python】【穆晨】【171224】连续第七十五天总结
- LeetCode Remove Duplicates from Sorted Array
- Python3.6 在win10下安装xlwings
- 反射之字段、方法、构造器的调用(二)
- 目前使用过的不经常使用的函数
- Redis 主从配置心得及其高可用方案
- git 初学使用
- python数据类型和变量
- LeetCode题解 第十五周
- Redis 内存淘汰机制