LeetCode #26 Remove Duplicates from Sorted Array
LeetCode #26 Remove Duplicates from Sorted Array
Question
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.
Solution
Approach #1
class Solution {
func removeDuplicates(_ nums: inout [Int]) -> Int {
if nums.count == 0 { return 0 }
var i = 0
for j in 1..<nums.count {
if nums[i] != nums[j] {
i += 1
nums[i] = nums[j]
}
}
return i + 1
}
}
Time complexity: O(n).
Space complexity: O(1).
转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/7066155.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步