26. Remove Duplicates from Sorted Array
来源:互联网 发布:手机淘宝怎么登陆卖家 编辑:程序博客网 时间:2024/05/21 07:47
26. Remove Duplicates from Sorted Array
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 class Solution { public int removeDuplicates(int[] nums) { if(nums.length==0) return 0; int len=1; for(int i=1;i<nums.length;i++){ if(nums[i]!=nums[i-1]){ nums[len]=nums[i]; len++; } } return len; }}
这个解法可以归结为“两个指针”问题。
【两个指针】因为这个数组已经排过序,所以我们可以用两个指针i和j,i表示跑得慢的,j表示跑得快的。只要nums[i]=nums[j],我们令j自增1来跳过这些重复元素。
当我们遇到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;}
Complexity analysis
Time complextiy : O(n). Assume that n is the length of array. Each of i and j traverses at most n steps.
Space complexity : O(1).
- [LeetCode]26.Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- LeetCode 26. Remove Duplicates from Sorted Array
- LeetCode --- 26. Remove Duplicates from Sorted Array
- LeetCode 26.Remove Duplicates from Sorted Array
- [Leetcode] 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 【leetcode】26. Remove Duplicates from Sorted Array
- 【leetcode】 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- [leetCode]26. Remove Duplicates from Sorted Array
- LeetCode 26.Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array LeetCode
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 【HDU2037】 今年暑假不AC(贪心,sort)
- 自学Unity3D游戏开发(1)
- 面试记录-数据开发/算法/JAVA
- Java 高并发基础
- 2017 Multi-University Training Contest
- 26. Remove Duplicates from Sorted Array
- 欢迎使用CSDN-markdown编辑器
- css选择器应用
- 手动建立数据集
- Angular入门之依赖注入
- JAVA学习记录---入门---for,each循环
- 【CodeForces
- TClientDataSet[2]: Data、XMLData
- 评分卡模型开发-定性指标筛选