Skip to content

Commit 3d95690

Browse files
authored
Merge pull request #2364 from acious/main
[acious] WEEK 01 solutions
2 parents 0383dda + c915105 commit 3d95690

3 files changed

Lines changed: 61 additions & 0 deletions

File tree

contains-duplicate/acious.kt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
// 1 <= nums.length <= 10^5
3+
// Integer.MIN_VALUE(2,147,483,647) < -10^9 <= nums[i] <= 10^9 < Integer.MAX_VALUE(2,147,483,647)
4+
// HashSet에 아이템을 하나씩 넣으면서 이미 존재하는 아이템이 있으면 true, 없으면 false
5+
// 시간복잡도 : O(n), 공간복잡도 : O(n)
6+
fun containsDuplicate(nums: IntArray): Boolean {
7+
val set = HashSet<Int>()
8+
for (num in nums) {
9+
if (set.contains(num)) {
10+
return true
11+
}
12+
set.add(num)
13+
}
14+
return false
15+
}
16+
}

top-k-frequent-elements/acious.kt

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
// 시간복잡도 : O(n) : map 세팅, O(nlogn) : map value 정렬 = O(nlogn)
3+
fun topKFrequent(nums: IntArray, k: Int): IntArray {
4+
val map = mutableMapOf<Int, Int>()
5+
6+
for (num in nums) {
7+
// 더 효율적이고 가독성 좋은 getOrDefault 사용
8+
map[num] = map.getOrDefault(num, 0) + 1
9+
}
10+
11+
// 1. value를 기준으로 내림차순 정렬 후 key만 추출
12+
val sortedKeys = map.entries
13+
.sortedByDescending { it.value }
14+
.map { it.key }
15+
16+
// 2. 0부터 k개(0 until k)를 자르고 IntArray로 변환
17+
return sortedKeys.slice(0 until k).toIntArray()
18+
}
19+
}

two-sum/acious.kt

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
// nums의 모든 숫자를 Map에 저장. key는 nums의 숫자, value는 해당 숫자의 인덱스
3+
// target의 숫자가 동일한 숫자가 더해져야 하는 케이스 (예: target = 4, nums = [2, 2])를 위해 value는 List로 저장
4+
// 시간복잡도: O(n), 공간복잡도: O(n)
5+
// improvement point : 한번의 루프를 순회하는 것으로도 문제를 해결할 수 있음.
6+
fun twoSum(nums: IntArray, target: Int): IntArray {
7+
val map = mutableMapOf<Int, MutableList<Int>>()
8+
for (index in nums.indices) { // nums.indices는 nums의 인덱스 범위를 반환
9+
val list = map.getOrDefault(nums[index], mutableListOf())
10+
list.add(index)
11+
map[nums[index]] = list
12+
}
13+
for (index in nums.indices) {
14+
val complement = target - nums[index]
15+
val complementIndices = map[complement]
16+
if (complementIndices != null) {
17+
for (complementIndex in complementIndices) {
18+
if (complementIndex != index) {
19+
return intArrayOf(index, complementIndex)
20+
}
21+
}
22+
}
23+
}
24+
throw IllegalArgumentException("No two sum solution")
25+
}
26+
}

0 commit comments

Comments
 (0)