forked from lexrus/LeetCode.swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path26.swift
73 lines (54 loc) · 2.03 KB
/
26.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
// RemoveDuplicatesFromSortedArray.swift
// RemoveDuplicatesFromSortedArray
//
// Created by Lex Tang on 4/21/15.
// Copyright (c) 2015 Lex Tang. All rights reserved.
//
/*
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 A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
*/
import Foundation
import XCTest
extension NSMutableArray {
// O(n)
func removeDuplicates() -> Int {
// In case there is nothing to do
if self.count == 0 {
return 0
}
var index = 0
for var i = 1; i < self.count; i++ {
let l: AnyObject = self.objectAtIndex(index)
let r: AnyObject = self.objectAtIndex(i)
if !l.isEqual(r) {
self.replaceObjectAtIndex(++index, withObject: r)
}
}
// Remove the remaining
self.removeObjectsInRange(NSRange(location: index + 1, length: self.count - index - 1))
return index + 1
}
}
class RemoveDuplicatesFromSortedArrayTest: XCTestCase {
func testRemoveDuplicatesFromSortedArray() {
let array0 = NSMutableArray(array: [1,1,2])
XCTAssertEqual(array0.removeDuplicates(), 2, "")
let array1 = NSMutableArray(array: [3,4,4,5,5,5,6])
XCTAssertEqual(array1.removeDuplicates(), 4, "")
XCTAssertEqual(array1, [3,4,5,6], "")
let array2 = NSMutableArray(array: [12, 12, 12, 12, 12])
XCTAssertEqual(array2.removeDuplicates(), 1, "")
XCTAssertEqual(array2, [12], "")
let array3 = NSMutableArray(array: [])
XCTAssertEqual(array3.removeDuplicates(), 0, "")
XCTAssertEqual(array3, [], "")
let array4 = NSMutableArray(array: ["a", "a", "b", "b", "b", "汉", "汉"])
XCTAssertEqual(array4.removeDuplicates(), 3, "")
XCTAssertEqual(array4, ["a", "b", "汉"], "")
}
}