diff --git a/3sum/kut7728.swift b/3sum/kut7728.swift new file mode 100644 index 000000000..6f300327b --- /dev/null +++ b/3sum/kut7728.swift @@ -0,0 +1,47 @@ +///정수 배열 nums가 주어졌을 때,세 수의 합이 0이 되는 모든 삼중 조합 [nums[i], nums[j], nums[k]]을 반환하세요. +///i, j, k 모두 다른 인덱스, 같은 조합의 결과는 하나로 취급 + +class Solution { + func threeSum(_ nums: [Int]) -> [[Int]] { + let sorted = nums.sorted() + var result = [[Int]]() + + for i in 0.. 0 && sorted[i] == sorted[i - 1] { + continue + } + + //포인터 설정 + var left = i + 1 + var right = sorted.count - 1 + + //두 포인터가 만나기 전까지만 + while left < right { + let sum = sorted[i] + sorted[left] + sorted[right] + + if sum == 0 { + result.append([sorted[i], sorted[left], sorted[right]]) + + // 같은 left/right 값 스킵 + while left < right && sorted[left] == sorted[left + 1] { + left += 1 + } + while left < right && sorted[right] == sorted[right - 1] { + right -= 1 + } + + left += 1 + right -= 1 + + } else if sum < 0 { + left += 1 + } else { + right -= 1 + } + } + } + + return result + } +} diff --git a/climbing-stairs/kut7728.swift b/climbing-stairs/kut7728.swift new file mode 100644 index 000000000..09fa6f8ca --- /dev/null +++ b/climbing-stairs/kut7728.swift @@ -0,0 +1,34 @@ +class Solution { + //계단 갯수 n 입력받음 + func climbStairs(_ n: Int) -> Int { + var result = 0 + + ///1계단씩 올라가는 경우 = 1스탭 + ///2계단씩 올라가는 경우 = 2스탭 + ///2스탭인 경우를 1씩 증가시켜줌 + for i in 0...(n/2) { + ///2스탭이 없는 경우 -> 전부 1스탭임 + if i == 0 { + result += 1 + continue + } + + ///n에서 2스탭 횟수를 빼서 1스탭 횟수 구하기 + let x = n - (2 * i) + + ///조합계산식 (2스탭,1스탭 전체 횟수 C 2스탭 횟수) + result += ncm(x+i, i) + } + + return result + } + + ///ncm함수로 조합 계산식을 구현 + func ncm(_ n: Int, _ m: Int) -> Int { + if m == 1 { return n } ///nC1 이라면 전체횟수 n 반환 + if m == n { return 1 } ///nCn 이라면 1반환 + + ///조합 계산식을 코드로 계산할 수 있도록 최적화하면 다음과 같아짐 + return (1...m).reduce(1) { $0 * ($1 + n-m)/$1 } + } +} diff --git a/product-of-array-except-self/kut7728.swift b/product-of-array-except-self/kut7728.swift new file mode 100644 index 000000000..157a7903e --- /dev/null +++ b/product-of-array-except-self/kut7728.swift @@ -0,0 +1,26 @@ +///정수배열 nums가 주어질때 정수배열 answer를 반환하시오 +///answer의 각 요소는 nums의 같은 인덱스의 요소를 제외한 나머지 요소의 곱 + +//복잡도 O(n) +class Solution { + func productExceptSelf(_ nums: [Int]) -> [Int] { //nums = 1,2,3,4 + let n = nums.count + var answer = [Int](repeating: 1, count: n) //answer = 1,1,1,1 + var left = [Int](repeating: 1, count: n) //left = 1,1,1,1 + + let revNums = Array(nums.reversed()) //revNums = 4,3,2,1 + var right = [Int](repeating: 1, count: n) //right = 1,1,1,1 + + for i in 1.. Bool { + ///둘이 문자 갯수가 다르다면 바로 False + if s.count != t.count { return false } + + ///해쉬테이블 사용 + var wordDic: [Character: Int] = [:] + + ///s의 글자들은 1씩 추가, t의 글자들은 1씩 감소 + for (sChar, tChar) in zip(s, t) { + wordDic[sChar, default: 0] += 1 + wordDic[tChar, default: 0] -= 1 + } + + ///딕셔너리의 모든 값이 상쇄되어 0이 되면 true + return wordDic.values.allSatisfy { $0 == 0 } + } +} diff --git a/validate-binary-search-tree/kut7728.swift b/validate-binary-search-tree/kut7728.swift new file mode 100644 index 000000000..97973e55d --- /dev/null +++ b/validate-binary-search-tree/kut7728.swift @@ -0,0 +1,45 @@ +/** + * 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 + * } + * } + */ + +//<문제> +///이진 트리의 루트가 주어졌을 때, 이것이 유효한 이진 검색 트리(BST)인지 판단하세요. +///유효한 BST는 다음과 같이 정의됩니다: +///- 노드의 왼쪽 하위 트리에는 노드의 키보다 작은 키를 가진 노드만 포함되고, +///- 노드의 오른쪽 하위 트리에는 노드의 키보다 큰 키를 가진 노드만 포함됩니다. +///- 또한 왼쪽과 오른쪽 하위 트리는 모두 이진 검색 트리여야 합니다. + +class Solution { + func isValidBST(_ root: TreeNode?) -> Bool { + return checkingBST(root, min: nil, max: nil) + } + + // min과 max는 현재 노드가 가질 수 있는 값의 범위 + func checkingBST(_ node: TreeNode?, min: Int?, max: Int?) -> Bool { + guard let node else { return true } // nil이면 유효한 트리 + + if let min = min, node.val <= min { + return false + } + if let max = max, node.val >= max { + return false + } + + // 왼쪽은 max = node.val, 오른쪽은 min = node.val + return checkingBST(node.left, min: min, max: node.val) + && checkingBST(node.right, min: node.val, max: max) + } +} +