File tree Expand file tree Collapse file tree 2 files changed +88
-0
lines changed
validate-binary-search-tree Expand file tree Collapse file tree 2 files changed +88
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments