Skip to content

Commit 8dc75d3

Browse files
committed
2 parents 17447e1 + d0df82d commit 8dc75d3

File tree

18 files changed

+455
-33
lines changed

18 files changed

+455
-33
lines changed

3sum/KwonNayeon.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,35 @@
33
1. 3 <= nums.length <= 3000
44
2. -10^5 <= nums[i] <= 10^5
55
6-
Time Complexity:
7-
- O(n^2) (정렬은 O(n log n), 이중 반복문은 O(n^2))
8-
Space Complexity:
9-
- O(n) (결과 리스트)
6+
Time Complexity: O(n^2)
7+
- 정렬은 O(n log n), 이중 반복문은 O(n^2)
8+
Space Complexity: O(n)
9+
- 결과 리스트를 저장하는 데 필요한 공간
10+
11+
풀이 방법:
12+
- 투 포인터를 활용하여 합이 0이 되는 세 수 조합 찾기
13+
- 배열 정렬: 투 포인터 사용 + 중복 처리 용이
14+
- for 루프: 첫 번째 숫자 선택 (len(nums)-2까지)
15+
- 중복된 첫 번째 숫자 건너뛰기
16+
- left, right 포인터 설정
17+
- while 루프: 두 포인터가 교차하지 않아야 함
18+
- sum = nums[i] + nums[left] + nums[right] 계산
19+
- sum == 0: 결과 추가, 중복 건너뛰기, 양쪽 포인터 이동
20+
- sum < 0: left 증가 (더 큰 값 필요)
21+
- sum > 0: right 감소 (더 작은 값 필요)
22+
- 최종 결과 반환
1023
"""
24+
# Brute-force: three nested loops → O(n^3)
25+
# Optimized: sort + two pointer → O(n^2)
1126

1227
class Solution:
1328
def threeSum(self, nums: List[int]) -> List[List[int]]:
29+
# Step 1: Sort the array
30+
# Step 2: Fix one number using for loop
31+
# Step 3: Use two pointers to find two other numbers
32+
# - if sum == 0: valid triplet
33+
# - if sum < 0: move left pointer
34+
# - if sum > 0: move right pointer
1435
nums.sort()
1536
result = []
1637

3sum/jiji-hoon96.ts

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[][]}
4+
*
5+
* 풀이 1
6+
*
7+
* 이렇게 푸니까 시간복잡도 O(n^3) / 공간복잡도 O(n) 라서 복잡한 예시에는 time limit 이 발생함
8+
* 개선해보자..
9+
*
10+
* function threeSum(nums: number[]): number[][] {
11+
* nums.sort((a, b) => a - b);
12+
* let result = []
13+
* for (let i= 0; i<nums.length; i++){
14+
* for(let j= i+1 ; j <nums.length; j++){
15+
* for (let k = j+1; k<nums.length; k++){
16+
* if(nums[i]+nums[j]+nums[k]===0){
17+
* result.push([nums[i], nums[j], nums[k]]);
18+
* }
19+
* }
20+
* }
21+
* }
22+
*
23+
* return Array.from(
24+
* new Set(result.map(item => JSON.stringify(item))),
25+
* str => JSON.parse(str)
26+
* );
27+
* }
28+
*
29+
* 풀이 2
30+
*
31+
* 투포인터를 활용해보자.
32+
* 아래처럼 문제를 풀게되면 시간복잡도 O(n^2) / 공간복잡도 O(1) 이다.
33+
* 시공간 복잡도가 줄긴하지만 메모리 사용량과 큰 숫자를 다룰 때 성능이 매우 좋다!
34+
*/
35+
36+
37+
function threeSum(nums: number[]): number[][] {
38+
let result : number[][] = []
39+
nums.sort((a, b) => a - b);
40+
const n = nums.length;
41+
42+
for(let first = 0; first<n-2; first++){
43+
// 첫번째가 양수면 0이 될 수 없음
44+
if(nums[first] > 0) break;
45+
46+
//중복된 수는 건너뜀
47+
if(first > 0 && nums[first]===nums[first-1]) continue;
48+
49+
let left = first + 1;
50+
let right = n-1;
51+
52+
while(left < right){
53+
const sum = nums[first] +nums[left] + nums[right];
54+
55+
if(sum < 0){
56+
left ++
57+
}else if(sum > 0){
58+
right --;
59+
}else{
60+
result.push([nums[first],nums[left],nums[right]]);
61+
// left, left+1 이 같을 때 중복된 수는 건너뜀
62+
while(left < right && nums[left] === nums[left+1]) left++;
63+
// right, right+1 이 같을 때 중복된 수는 건너뜀
64+
while(left < right && nums[right] === nums[right-1]) right--;
65+
left++;
66+
right--;
67+
}
68+
}
69+
}
70+
return result;
71+
}

climbing-stairs/jiji-hoon96.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @param n
3+
*
4+
* dp, 슬라이딩 윈도우 사용해서 풀 수 있다.
5+
*
6+
* 공간 복잡도를 줄이기 위해서 아래와같이 슬라이딩을 활용할 수 있다.
7+
*
8+
* function climbStairs(n: number): number {
9+
* if (n <= 2) return n;
10+
*
11+
* let first = 1; // 1계단을 오르는 방법 수
12+
* let second = 2; // 2계단을 오르는 방법 수
13+
*
14+
* for (let i = 3; i <= n; i++) {
15+
* let current = first + second;
16+
* first = second;
17+
* second = current;
18+
* }
19+
*
20+
* return second;
21+
* }
22+
*/
23+
24+
25+
function climbStairs(n: number): number {
26+
if(n <= 2) return n;
27+
28+
let dp: number[] = new Array(n+1);
29+
dp[1] = 1;
30+
dp[2] = 2;
31+
32+
for(let i=3;i<=n;i++){
33+
dp[i] = dp[i-1] +dp[i-2];
34+
}
35+
36+
return dp[n]
37+
};

contains-duplicate/JisuuungKim.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def containsDuplicate(self, nums: List[int]) -> bool:
3+
count = {}
4+
5+
for i in nums:
6+
if i in count:
7+
return True
8+
else:
9+
count[i] = 1
10+
11+
return False

contains-duplicate/ayleeee.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
class Solution:
2+
def containsDuplicate(self, nums: List[int]) -> bool:
3+
return len(set(nums))!=len(nums)
4+
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import java.util.HashSet;
2+
3+
class Solution {
4+
public boolean containsDuplicate(int[] nums) {
5+
HashSet<Integer> numSet = new HashSet<>();
6+
7+
for (int i = 0; i < nums.length; i++) {
8+
9+
if (numSet.contains(nums[i])) {
10+
return true;
11+
}
12+
numSet.add(nums[i]);
13+
}
14+
15+
return false;
16+
}
17+
}

contains-duplicate/toychip.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import java.util.HashSet;
2+
import java.util.Set;
3+
4+
class Solution {
5+
public boolean containsDuplicate(int[] nums) {
6+
Set<Integer> answer = new HashSet<>();
7+
for (int num : nums) {
8+
if (!answer.contains(num)) {
9+
answer.add(num);
10+
} else {
11+
return true;
12+
}
13+
}
14+
return false;
15+
}
16+
}
Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,32 @@
11
"""
22
Constraints:
3-
1. 2 <= nums.length <= 10^5
4-
2. -30 <= nums[i] <= 30
5-
3. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer
3+
- 나눗셈 연산 사용 불가능
4+
- O(n) 시간 복잡도로 구현해야 함
5+
- 모든 prefix/suffix 곱은 32비트 정수 범위 내에 있음
66
77
Time Complexity: O(n)
8-
- 배열을 두 번 순회하므로 O(n)
8+
- 배열을 두 번만 순회
99
1010
Space Complexity: O(1)
11-
- 출력 배열(answer)을 제외하면 추가 공간이 상수만큼만 필요(left, right 변수)
11+
- 출력 배열 추가 공간은 상수만 사용 (left, right 변수)
1212
1313
풀이 방법:
14-
1. answer 배열을 1로 초기화 (곱셈에서는 1이 영향을 주지 않음)
15-
2. 왼쪽에서 오른쪽으로 순회:
16-
- answer[i]에 현재까지의 left 누적값을 곱함
17-
- left *= nums[i]로 다음을 위해 left 값을 업데이트
18-
3. 오른쪽에서 왼쪽으로 순회 (range(n-1, -1, -1) 사용):
19-
- answer[i]에 현재까지의 right 누적값을 곱함
20-
- right *= nums[i]로 다음을 위해 right 값을 업데이트
14+
- 각 위치의 결과는 (왼쪽 모든 요소의 곱) * (오른쪽 모든 요소의 곱)
15+
- 두 번의 순회로 이를 계산:
16+
1. 왼쪽 -> 오른쪽: 각 위치에 왼쪽 모든 요소의 누적 곱 저장
17+
2. 오른쪽 -> 왼쪽: 각 위치에 오른쪽 모든 요소의 누적 곱을 곱함
18+
19+
예시: nums = [1, 2, 3, 4]
20+
1단계 후: answer = [1, 1, 2, 6]
21+
2단계 후: answer = [24, 12, 8, 6]
2122
"""
2223

24+
# Final result = (product of all elements on the left side) * (product of all elements on the right side)
25+
26+
# Step 1: Initialize result array with 1s
27+
# Step 2: Traverse from left to right, storing cumulative product of left side
28+
# Step 3: Traverse from right to left, multiplying with cumulative product of right side
29+
# nums = [1,2,3,4]
2330
class Solution:
2431
def productExceptSelf(self, nums: List[int]) -> List[int]:
2532
n = len(nums)
@@ -29,10 +36,11 @@ def productExceptSelf(self, nums: List[int]) -> List[int]:
2936
for i in range(n):
3037
answer[i] *= left
3138
left *= nums[i]
32-
39+
# answer = [1, 1, 2, 6] at this point
3340
right = 1
3441
for i in range(n-1, -1, -1):
3542
answer[i] *= right
3643
right *= nums[i]
37-
44+
3845
return answer
46+
# answer = [24,12,8,6]
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
*
3+
* 풀이 1
4+
*
5+
* 아래와 같이 문제를 푸니, 성능적으로 문제가 발생했다.
6+
* 시간복잡도는 0(n2) / 공간 복잡도는 0(n)
7+
*
8+
* function productExceptSelf(nums: number[]): number[] {
9+
* if(nums.every(num => num === 0)) return nums; 시간 복잡도 0(n)
10+
* if(nums.length > 2 && nums.filter(num=> num ===0).length > 1) return new Array(nums.length).fill(0) 시간 복잡도 0(n) 공간 복잡도 0(n)
11+
* let result = [] 공간 복잡도 0(n)
12+
* for(let i =0;i<nums.length; i++){ 시간 복잡도 0(n)
13+
* let multi = 1;
14+
* const a= nums.filter((num,index)=> index !== i); 시간 복잡도 0(n) 공간 복잡도 0(n)
15+
* for(let item of a){ 시간 복잡도 0(n)
16+
* multi *= item
17+
* }
18+
* result.push(multi)
19+
* }
20+
* return result
21+
* };
22+
*
23+
* 풀이 2 는 누적합 알고리즘을 사용해서 왼쪽 방향에서 시작해 오른쪽 방향으로 곱하는 방식으로 문제 해결
24+
*
25+
*/
26+
27+
function productExceptSelf(nums: number[]): number[] {
28+
const n = nums.length;
29+
const result = new Array(n).fill(1);
30+
31+
let leftProduct = 1;
32+
for (let i = 0; i < n; i++) {
33+
result[i] *= leftProduct;
34+
leftProduct *= nums[i];
35+
}
36+
37+
let rightProduct = 1;
38+
for (let i = n - 1; i >= 0; i--) {
39+
result[i] *= rightProduct;
40+
rightProduct *= nums[i];
41+
}
42+
43+
return result;
44+
}

top-k-frequent-elements/KwonNayeon.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,17 @@
11
"""
2-
Title: 237. Top K Frequent Elements
3-
Link: https://leetcode.com/problems/top-k-frequent-elements/
4-
5-
Question:
6-
- Given an integer array `nums` and an integer `k`, return the `k` most frequent elements.
7-
- You may return the answer in any order.
2+
Problem: 237. Top K Frequent Elements
83
94
Constraints:
10-
- 1 <= nums.length <= 10^5
11-
- -10^4 <= nums[i] <= 10^4
12-
- k is in the range [1, the number of unique elements in the array].
13-
- The answer is guaranteed to be unique.
5+
- 1 <= nums.length <= 10^5
6+
- -10^4 <= nums[i] <= 10^4
7+
- k is in the range [1, the number of unique elements in the array].
8+
- The answer is guaranteed to be unique.
9+
10+
Time Complexity: O(n log n)
11+
-
1412
15-
Time Complexity:
16-
- O(n log n)
17-
Space Complexity:
18-
- O(n)
13+
Space Complexity: O(n)
14+
-
1915
"""
2016

2117
# Original Solution

0 commit comments

Comments
 (0)