26. Remove Duplicates from Sorted Array
来源:互联网 发布:linux系统改编码 编辑:程序博客网 时间:2024/05/24 06: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 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.
这个题我刚看的时候感觉很简单,也没有仔细看,直接就把数组存进了set里,结果submit不过,细看下才发现原来是个sorted数组!审题很重要……
思路如下:
用cur表示不重复的数组的长度,即最后要返回的去重后的数组长度。从下标1开始循环遍历数组,如果第i-1和第i个不相等,那么就将第i个的值赋值给第cur个,这样遍历数组后,数组的前cur个元素就是我们要的去重后的数组。例如数组[1,1,2,2,3,4],按此原理执行一遍后变成了[1,2,3,4,3,4]
代码如下:
class Solution {
func removeDuplicates(_ nums: inout [Int]) -> Int {
if nums.count < 1 {
return 0
}
var cur: Int = 1
for i in 1..<nums.count {
if nums[i-1] != nums[i] {
nums[cur] = nums[i]
cur = cur + 1
}
}
return cur
}
}
运行时间:
39ms
- [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
- JVM垃圾收集算法及垃圾收集器
- eclipse常用快捷键
- (三)语音识别概述
- RxJava+Retrofit+OkHttp深入浅出-mvp(使用篇)
- 路径规划-快速搜索随机树(Rapid-exploration Random Tree)
- 26. Remove Duplicates from Sorted Array
- ImageView的属性android:scaleType
- html multi language switch
- java IO最详解
- 美团点评Android客户端融合架构演进之路
- opencv中mask图像合成扩充数据集
- 顶点插值片元
- Jquery修改image的src属性,图片不加载问题
- Spark-2.0 搭建源码阅读环境