Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions non-overlapping-intervals/sonjh1217.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution {
/// 구간을 다루는데, 겹치지 않게 최대/최소로 뽑는 문제 -> 끝점 기준 정렬 + 그리디
/// 가장 빨리 끝나는 것들을 선택해야 최대한 많이 선택할 수 있음
/// 끝점 기준 오름차순 정렬 nlogn
/// 순차적으로 돌면서 겹치면 제거(앞 것들보다 끝점이 더 뒤라서, 시작만 확인하면 됨)
/// O(nlogn) time / O(n) space
func eraseOverlapIntervals(_ intervals: [[Int]]) -> Int {
let intervals = intervals.sorted { $0[1] < $1[1] }
var end = intervals[0][1]
var removal = 0

for i in 1..<intervals.count {
let isOverlapping = intervals[i][0] < end
if isOverlapping {
removal += 1
} else {
end = intervals[i][1]
}
}

return removal
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Solution {
// O(n+m) (m = edges.count) time / O(n+m) space
func countComponents(_ n: Int, _ edges: [[Int]]) -> Int {
var graph = [[Int]](repeating: [], count: n)
for edge in edges {
graph[edge[0]].append(edge[1])
graph[edge[1]].append(edge[0])
}

var visited = [Bool](repeating: false, count: n)
var connectedComponents = 0

for i in 0..<n {
if visited[i] {
continue
}
var queue = [Int]()
queue.append(i)
visited[i] = true
var head = 0

while queue.count > head {
let current = queue[head]
head += 1

for node in graph[current] {
if !visited[node] {
visited[node] = true
queue.append(node)
}
}
}
connectedComponents += 1
}

return connectedComponents
}
}

50 changes: 50 additions & 0 deletions remove-nth-node-from-end-of-list/sonjh1217.swift
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2가지 풀이 덕분에 공부가 많이 됐습니다. 감사합니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
// O(n) time / O(n) space
func removeNthFromEndList(_ head: ListNode?, _ n: Int) -> ListNode? {
var nodes = [ListNode]()
var node = head
while let current = node {
nodes.append(current)
node = current.next
}

let indexToRemove = nodes.count - n

if indexToRemove == 0 {
return head?.next
}

nodes[indexToRemove - 1].next = indexToRemove + 1 < nodes.count ? nodes[indexToRemove + 1] : nil
return head
}

// O(n) time / O(1) space
func removeNthFromEndPointer(_ head: ListNode?, _ n: Int) -> ListNode? {
let dummy = ListNode(0)
dummy.next = head
var post: ListNode? = dummy
var prev: ListNode? = dummy

for _ in 0...n {
post = post?.next
}

while post != nil {
prev = prev?.next
post = post?.next
}

prev?.next = prev?.next?.next
return dummy.next
}
}
30 changes: 30 additions & 0 deletions same-tree/sonjh1217.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
// O(n) time, O(h) space h = 트리의 높이. 최악: n, 평균: log n
func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
switch (p, q) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

swift에서는 switch문에 어떤 값을 넣을 수 있는건가요? JavaScript에서는 하나의 변수 또는 표현식을 사용할 수 있어서 궁금합니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(p, q)는 튜플 타입입니다. 컴마로 분리된 리스트타입이구 ()로 감싸요! https://docs.swift.org/swift-book/documentation/the-swift-programming-language/types/ switch에는 value가 들어갑니다 https://docs.swift.org/swift-book/documentation/the-swift-programming-language/controlflow/ 질문 주셔서 저도 정확히 알았네용 감사합니다

case (nil, nil):
return true
case let (p?, q?):
return p.val == q.val
&& isSameTree(p.left, q.left)
&& isSameTree(p.right, q.right)
default:
return false
}
}
}
87 changes: 87 additions & 0 deletions serialize-and-deserialize-binary-tree/sonjh1217.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/

class Codec {
// O(n) time / O(n) space
func serialize(_ root: TreeNode?) -> String {
var serializedNodes = [String]()
var queueNodes = [TreeNode?]()
queueNodes.append(root)
var head = 0

while head < queueNodes.count {
let node = queueNodes[head]
head += 1

if let node {
serializedNodes.append("\(node.val)")

queueNodes.append(node.left)
queueNodes.append(node.right)
} else {
serializedNodes.append("null")
}

}

return serializedNodes.joined(separator: ",")
}

// O(n) time / O(n) space
func deserialize(_ data: String) -> TreeNode? {
let serializedTree = data
var nodeVals = serializedTree.split(separator: ",")

guard let first = nodeVals.first,
let firstVal = Int(first) else {
return nil
}

let root = TreeNode(firstVal)
var queueNodes = [TreeNode]()
queueNodes.append(root)
var head = 0
var isLeft = true

for i in 1..<nodeVals.count {
let node = queueNodes[head]
let stringValue = nodeVals[i]
let val = Int(stringValue)

if isLeft {
if let val {
let leftNode = TreeNode(val)
node.left = leftNode
queueNodes.append(leftNode)
} else {
node.left = nil
}
} else {
if let val {
let rightNode = TreeNode(val)
node.right = rightNode
queueNodes.append(rightNode)
} else {
node.right = nil
}
head += 1
}
isLeft.toggle()
}

return root
}
}