-
Notifications
You must be signed in to change notification settings - Fork 2
/
905.Sort-Array-By-Parity.swift
48 lines (44 loc) · 1.18 KB
/
905.Sort-Array-By-Parity.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
/**
* Question Link: https://leetcode.com/problems/sort-array-by-parity/
*/
class Solution {
/// One pass, with new array
/// Time Complexity: O(n), Space Complexity: O(n)
func sortArrayByParity(_ nums: [Int]) -> [Int] {
guard nums.count > 1 else { return nums }
var result = [Int](repeating: 0, count: nums.count)
var i = 0
var j = nums.count-1
for n in nums {
if n % 2 == 0 {
result[i] = n
i += 1
} else {
result[j] = n
j -= 1
}
}
return result
}
/// In place, two pointers
/// Time Complexity: O(n), Space Complexity: O(1)
func sortArrayByParity2(_ nums: inout [Int]) -> [Int] {
guard nums.count > 1 else { return nums }
var i = 0
var j = nums.count-1
while i < j {
if nums[i] % 2 == 1 && nums[j] % 2 == 0 {
nums.swapAt(i,j)
i += 1
j -= 1
}
if nums[i] % 2 == 0 { i += 1 }
if nums[j] % 2 == 1 { j -= 1 }
}
return nums
}
}
assert(Solution().sortArrayByParity([3,1,2,4]) == [2,4,1,3])
assert(Solution().sortArrayByParity([3]) == [3])
assert(Solution().sortArrayByParity([3,4,1,2,5,7,8,10]) == [4, 2, 8, 10, 7, 5, 1, 3])
print("PASS")