Skip to content

Commit c3ca3c3

Browse files
Added new accepted solutions
1 parent a06e6ef commit c3ca3c3

File tree

22 files changed

+543
-0
lines changed

22 files changed

+543
-0
lines changed

0015-3Sum.playground/Contents.swift

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// LeetCode: https://leetcode.com/problems/3sum/description/
2+
// Hint: Start from TwoSum, use sorting
3+
4+
class Solution {
5+
func threeSum(_ nums: [Int]) -> [[Int]] {
6+
guard nums.count >= 3 else {
7+
return []
8+
}
9+
nums.sorted()
10+
var idxArr: [[Int]] = []
11+
var pair: [[Int]] = []
12+
var num1: [Int] = []
13+
for idx1 in 0..<nums.count {
14+
if num1.contains(nums[idx1]) {
15+
break
16+
}
17+
num1.append(nums[idx1])
18+
for idx2 in idx1+1..<nums.count {
19+
if pair.contains([nums[idx1], nums[idx2]].sorted()) {
20+
continue
21+
} else {
22+
pair.append([nums[idx1], nums[idx2]].sorted())
23+
idxArr.append([idx1, idx2])
24+
}
25+
}
26+
}
27+
var output: [[Int]] = []
28+
for i in 0..<nums.count {
29+
for pair in idxArr {
30+
if i == pair[0] || i == pair[1] {
31+
continue
32+
}
33+
34+
if nums[i] + nums[pair[0]] + nums[pair[1]] == 0, !output.contains([nums[i], nums[pair[0]], nums[pair[1]]].sorted()) {
35+
output.append([nums[i], nums[pair[0]], nums[pair[1]]].sorted())
36+
}
37+
}
38+
}
39+
return output
40+
}
41+
}
42+
43+
let solution = Solution()
44+
print("\(solution.threeSum([-1, 0, 1, 2, -1, -4]))")
45+
print("---------------------------------")
46+
/**
47+
The solution set is:
48+
[
49+
[-1, 0, 1],
50+
[-1, -1, 2]
51+
]
52+
*/
53+
print("\(solution.threeSum([-1,0,1,0]))")
54+
print("---------------------------------")
55+
/**
56+
The solution set is:
57+
[
58+
[-1, 0, 1]
59+
]
60+
*/
61+
print("\(solution.threeSum([3,0,-2,-1,1,2]))")
62+
print("---------------------------------")
63+
/**
64+
The solution set is:
65+
[
66+
[-2, -1, 3],
67+
[-2, 0, 2],
68+
[-1, 0, 1]
69+
]
70+
*/
71+
let longArray1 = [-2,10,-14,11,5,-4,2,0,-10,-10,5,7,-11,10,-2,-5,2,12,-5,14,-11,-15,-5,12,0,13,8,7,10,6,-9,-15,1,14,11,-9,-13,-10,6,-8,-5,-11,6,-9,14,11,-7,-6,8,3,-7,5,-5,3,2,10,-6,-12,3,11,1,1,12,10,-8,0,8,-5,6,-8,-6,8,-12,-14,7,9,12,-15,-12,-2,-4,-4,-12,6,7,-3,-6,-14,-8,4,4,9,-10,-7,-4,-3,1,11,-1,-8,-12,9,7,-9,10,-1,-14,-1,-8,11,12,-5,-7]
72+
print(longArray1.count)
73+
print("\(solution.threeSum(longArray1))") // Test time limit
74+
print("---------------------------------")
75+
let longArray2 = [12,-14,-5,12,-2,9,0,9,-3,-3,-14,-6,-4,13,-11,-8,0,5,-7,-6,-10,-13,-7,-14,-3,0,12,5,-8,7,3,-11,0,6,9,13,-8,-6,7,4,6,0,13,-13,-1,9,-13,6,-1,-13,-15,-4,-11,-15,-11,-7,1,-14,13,8,0,2,4,-15,-15,-2,5,-8,7,-11,11,-10,4,1,-15,10,-5,-13,2,1,11,-6,4,-15,-5,8,-7,3,1,-9,-4,-14,0,-15,8,0,-1,-2,7,13,2,-5,11,13,11,11]
76+
print(longArray2.count)
77+
print("\(solution.threeSum(longArray2))") // Test time limit
78+
print("---------------------------------")
79+
print("\(solution.threeSum([-2,0,1,1,2]))")
80+
/**
81+
The solution set is:
82+
[
83+
[-2,0,2],
84+
[-2,1,1]
85+
]
86+
*/
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='macos'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// LeetCode: https://leetcode.com/problems/3sum-closest/description/
2+
// Simple math
3+
4+
class Solution {
5+
func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
6+
var sortedN = nums.sorted()
7+
var pairs: [Int: [Int]] = [:]
8+
var i = 0
9+
while i < sortedN.count {
10+
var k = i + 1
11+
while k < sortedN.count {
12+
let comp = target - sortedN[k] - sortedN[i]
13+
if nil == pairs[comp] {
14+
pairs[comp] = [i, k]
15+
}
16+
k += 1
17+
}
18+
i += 1
19+
}
20+
var output: Int?
21+
var third = 0
22+
while third < sortedN.count {
23+
for pair in pairs {
24+
if !pair.value.contains(third) {
25+
if pair.key == sortedN[third] {
26+
return target
27+
} else {
28+
if nil == output {
29+
output = target - pair.key + sortedN[third]
30+
} else if abs(pair.key - sortedN[third]) < abs(target - output!) {
31+
output = target - pair.key + sortedN[third]
32+
}
33+
}
34+
}
35+
}
36+
third += 1
37+
}
38+
return output!
39+
}
40+
}
41+
42+
let solution = Solution()
43+
print("\(solution.threeSumClosest([-1, 2, 1, -4], 1))") // 2
44+
print("\(solution.threeSumClosest([-3,-2,-5,3,-4], -1))") // -2
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='macos'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// LeetCode: https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
2+
3+
public class ListNode {
4+
public var val: Int
5+
public var next: ListNode?
6+
public init(_ val: Int, _ next: ListNode?) {
7+
self.val = val
8+
self.next = next
9+
}
10+
}
11+
12+
class Solution {
13+
func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
14+
guard let head = head else {
15+
return nil
16+
}
17+
var arr = convertToArray(head)
18+
let index = arr.count - n - 1
19+
guard index > 0 else {
20+
return nil
21+
}
22+
arr[index].next = arr[index + 2]
23+
return head
24+
}
25+
26+
private func convertToArray(_ head: ListNode) -> [ListNode] {
27+
var node: ListNode? = head
28+
var arr: [ListNode] = []
29+
while nil != node {
30+
arr.append(node!)
31+
node = node?.next
32+
}
33+
return arr
34+
}
35+
36+
func printLinkedList(_ head: ListNode) {
37+
var printedStr = ""
38+
var currentNode: ListNode? = head
39+
while nil != currentNode {
40+
printedStr.append("\(currentNode?.val ?? -1)")
41+
if nil != currentNode?.next {
42+
printedStr.append(", ")
43+
}
44+
currentNode = currentNode?.next
45+
}
46+
print(printedStr)
47+
}
48+
}
49+
50+
let solution = Solution()
51+
let node5 = ListNode(5, nil)
52+
let node4 = ListNode(4, node5)
53+
let node3 = ListNode(3, node4)
54+
let node2 = ListNode(2, node3)
55+
let node1 = ListNode(1, node2)
56+
solution.printLinkedList(node1)
57+
solution.removeNthFromEnd(node1, 2)
58+
solution.printLinkedList(node1)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='macos'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// LeetCode: https://leetcode.com/problems/valid-parentheses/description/
2+
3+
class Solution {
4+
func isValid(_ s: String) -> Bool {
5+
var arr: [Character] = []
6+
for c in s {
7+
switch c {
8+
case "(", "[", "{":
9+
arr.append(c)
10+
case ")":
11+
let char = pop(&arr)
12+
if nil == char || char != "(" {
13+
return false
14+
}
15+
case "]":
16+
let char = pop(&arr)
17+
if nil == char || char != "[" {
18+
return false
19+
}
20+
case "}":
21+
let char = pop(&arr)
22+
if nil == char || char != "{" {
23+
return false
24+
}
25+
default:
26+
break
27+
}
28+
}
29+
return arr.count == 0
30+
}
31+
32+
private func pop(_ arr: inout [Character]) -> Character? {
33+
guard arr.count > 0 else {
34+
return nil
35+
}
36+
return arr.remove(at: arr.count-1)
37+
}
38+
}
39+
40+
let solution = Solution()
41+
print("\(solution.isValid("()"))")
42+
print("\(solution.isValid("()[]{}"))")
43+
print("\(solution.isValid("(]"))")
44+
print("\(solution.isValid("([)]"))")
45+
print("\(solution.isValid("{[]}"))")
46+
print("\(solution.isValid("["))")
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='macos'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// LeetCode: https://leetcode.com/problems/merge-k-sorted-lists/description/
2+
3+
public class ListNode {
4+
public var val: Int
5+
public var next: ListNode?
6+
public init(_ val: Int) {
7+
self.val = val
8+
self.next = nil
9+
}
10+
}
11+
12+
class Solution {
13+
func mergeKLists(_ lists: [ListNode?]) -> ListNode? {
14+
var arr: [Int] = []
15+
for head in lists {
16+
arr = arr + toArray(head)
17+
}
18+
arr = arr.sorted()
19+
return toLinkedList(arr: arr)
20+
}
21+
private func toArray(_ head: ListNode?) -> [Int] {
22+
guard nil != head else {
23+
return []
24+
}
25+
var arr: [Int] = []
26+
var node = head
27+
while nil != node {
28+
arr.append((node?.val)!)
29+
node = node?.next
30+
}
31+
return arr
32+
}
33+
private func toLinkedList(arr: [Int]) -> ListNode? {
34+
guard arr.count > 0 else {
35+
return nil
36+
}
37+
guard arr.count > 1 else {
38+
return ListNode(arr[0])
39+
}
40+
var head = ListNode(arr[0])
41+
var node: ListNode? = ListNode(arr[1])
42+
head.next = node
43+
var index = 1
44+
while index + 1 < arr.count {
45+
node?.next = ListNode(arr[index+1])
46+
node = node?.next
47+
index += 1
48+
}
49+
return head
50+
}
51+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// LeetCode: https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
2+
3+
class Solution {
4+
func removeDuplicates(_ nums: inout [Int]) -> Int {
5+
var dict: [Int:Int] = [:]
6+
var newNums: [Int] = []
7+
for num in nums {
8+
if dict[num] == nil {
9+
dict[num] = 1
10+
newNums.append(num)
11+
}
12+
}
13+
nums = newNums
14+
return dict.count
15+
}
16+
}
17+
18+
let solution = Solution()
19+
var arr1 = [0,0,1,1,1,2,2,3,3,4]
20+
print("\(solution.removeDuplicates(&arr1))")
21+
print("\(arr1)")
22+
23+
var arr2 = [1,1,2]
24+
print("\(solution.removeDuplicates(&arr2))")
25+
print("\(arr2)")
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// LeetCode: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/
2+
3+
class Solution {
4+
func removeDuplicates(_ nums: inout [Int]) -> Int {
5+
guard nums.count > 0 else {
6+
return 0
7+
}
8+
var idx = 1
9+
var count = 1
10+
var preVal = nums[0]
11+
while idx < nums.count {
12+
if nums[idx] == preVal {
13+
if count == 2 {
14+
nums.remove(at: idx)
15+
} else {
16+
count += 1
17+
preVal = nums[idx]
18+
idx += 1
19+
}
20+
} else {
21+
count = 1
22+
preVal = nums[idx]
23+
idx += 1
24+
}
25+
26+
}
27+
return nums.count
28+
}
29+
}
30+
31+
let solution = Solution()
32+
var arr1 = [1,1,1,2,2,3]
33+
print("\(solution.removeDuplicates(&arr1))")
34+
print("\(arr1)")
35+
36+
var arr2 = [0,0,1,1,1,1,2,3,3]
37+
print("\(solution.removeDuplicates(&arr2))")
38+
print("\(arr2)")
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='macos'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

0 commit comments

Comments
 (0)