-
-
Notifications
You must be signed in to change notification settings - Fork 245
[kut7728] WEEK 02 solutions #1224
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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..<sorted.count { | ||
// 중복 값 스킵 | ||
if i > 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 | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 } | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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..<n { //i = 1,2,3 | ||
left[i] = left[i-1] * nums[i-1] //left = 1,1,2,6 | ||
right[i] = right[i-1] * revNums[i-1] //right = 1,4,12,24 | ||
} | ||
|
||
for i in answer.indices { | ||
answer[i] = left[i] * right[n-i-1] | ||
} | ||
|
||
return answer | ||
|
||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
//문자열 s, t를 받고, t가 s의 애너그램이면 true, 아니면 false 출력 | ||
|
||
class Solution { | ||
func isAnagram(_ s: String, _ t: String) -> 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 } | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
} | ||
} | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
아예 조건으로 상쇄되는 경우를 체크하는 건 좋은 방법이네요! 참고하겠습니다.