-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy path26_RemoveDuplicatesFromSortedArray.swift
54 lines (47 loc) · 1.22 KB
/
26_RemoveDuplicatesFromSortedArray.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//
// 26_RemoveDuplicatesFromSortedArray.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-11-05.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:26 Remove Duplicates from sorted array
URL: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Space: O(N)
Time: O(N)
*/
class RemoveDuplicatesFromSortedArray_Solution {
func removeDuplicates(_ nums: inout [Int]) -> Int {
guard nums.count > 1 else {
return nums.count
}
var lastFoundUnrepeatedIndex = 0
// Add in a local tmp to reduce array index query and improve performance.
var currentComparisonElement = nums[lastFoundUnrepeatedIndex]
for num in nums {
if num != currentComparisonElement {
lastFoundUnrepeatedIndex += 1
nums[lastFoundUnrepeatedIndex] = num
currentComparisonElement = num
}
}
return lastFoundUnrepeatedIndex + 1
}
func brilliant(_ nums: inout [Int]) -> Int {
guard nums.count > 1 else {
return nums.count
}
var i = 0
var lastValid = nums[0]
for num in nums {
if i < 1 || num > lastValid {
nums[i] = num
i += 1
lastValid = num
}
}
return i
}
}