Skip to content

Commit 51bf3f2

Browse files
committed
solution 3sum,valid-binary-search-tree
1 parent 5d5255c commit 51bf3f2

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

โ€Ž3sum/HISEHOONAN.swift

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//
2+
// 241.swift
3+
// Algorithm
4+
//
5+
// Created by ์•ˆ์„ธํ›ˆ on 4/8/25.
6+
//
7+
8+
//3Sum
9+
class Solution { //์ •๋ ฌ + two pointer
10+
func threeSum(_ nums: [Int]) -> [[Int]] {
11+
let nums = nums.sorted() //๋ฐฐ์—ด์„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ
12+
var result: [[Int]] = [] // ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•  ๋ฐฐ์—ด.
13+
14+
for i in 0..<nums.count { // i๋ฅผ 0๋ฒˆ์งธ ๋ฐฐ์—ด๋ถ€ํ„ฐ ์ˆœํšŒ.
15+
if i > 0 && nums[i] == nums[i - 1] {
16+
continue
17+
}
18+
19+
var left = i + 1 //left๋Š” i+1๋ฒˆ์งธ ์ธ๋ฑ์Šค
20+
var right = nums.count - 1 //right๋Š” ๋ฐฐ์—ด์˜ ๋๋ฒˆ์งธ ์ธ๋ฑ์Šค
21+
22+
while left < right {
23+
let sum = nums[i] + nums[left] + nums[right]
24+
25+
if sum == 0 {
26+
result.append([nums[i], nums[left], nums[right]])
27+
28+
// ์ค‘๋ณต ์ œ๊ฑฐ
29+
while left < right && nums[left] == nums[left + 1] {
30+
left += 1
31+
}
32+
while left < right && nums[right] == nums[right - 1] {
33+
right -= 1
34+
}
35+
36+
left += 1
37+
right -= 1
38+
} else if sum < 0 {
39+
left += 1
40+
} else {
41+
right -= 1
42+
}
43+
}
44+
}
45+
46+
return result
47+
}
48+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//
2+
// 251.swift
3+
// Algorithm
4+
//
5+
// Created by ์•ˆ์„ธํ›ˆ on 4/8/25.
6+
//
7+
8+
//Validate Binary Search Tree
9+
10+
/**
11+
* Definition for a binary tree node.
12+
* public class TreeNode {
13+
* public var val: Int
14+
* public var left: TreeNode?
15+
* public var right: TreeNode?
16+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
17+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
18+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
19+
* self.val = val
20+
* self.left = left
21+
* self.right = right
22+
* }
23+
* }
24+
*/
25+
26+
class Solution {
27+
func isValidBST(_ root: TreeNode?) -> Bool {
28+
return validate(root, min: nil, max: nil)
29+
}
30+
31+
private func validate(_ node: TreeNode?, min: Int?, max: Int?) -> Bool {
32+
guard let node = node else { return true }
33+
34+
if let min = min, node.val <= min { return false }
35+
if let max = max, node.val >= max { return false }
36+
37+
return validate(node.left, min: min, max: node.val) &&
38+
validate(node.right, min: node.val, max: max)
39+
}
40+
}

0 commit comments

Comments
ย (0)