Skip to content

[박종훈] 5주차 답안 제출 #102

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 1 commit into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions 3sum/dev-jonghoonpark.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
- 문제 : https://leetcode.com/problems/3sum/
- time complexity : O(n^2)
- space complexity : O(1) (결과값을 고려하지 않은 알고리즘 자체의 공간 복잡도)
Copy link
Contributor

@SamTheKorean SamTheKorean May 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 이부분이 궁금했는데 결과값을 고려하지 않는다는 걸 따로 명시하지 않아도 결과값을 고려하지 않는게 당연한 걸까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

조합이 어떻게 나오냐에 따라서 공간복잡도가 달라질 것 같아서 저도 뭐라고 적을까 고민하다가
달레님 블로그를 보니깐 위와같이 표현하신것 같아서 참고해보았습니다 : )

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아 그렇군요! 설명 감사합니다!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

출력 결과 때문에 반드시 필요한 메모리 사용량은 공간 복잡도 분석을 할 때는 무시하는 것이 일반적입니다.

- 블로그 링크 : https://algorithm.jonghoonpark.com/2024/05/07/leetcode-15

```java
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);

List<List<Integer>> result = new ArrayList<>();

int lastOne = Integer.MIN_VALUE;
for (int i = 0; i < nums.length - 1; i++) {
int num = nums[i];
if (lastOne == num) {
continue;
}

twoSum(result, nums, i);
lastOne = num;
}

return result;
}

public void twoSum(List<List<Integer>> result, int[] nums, int targetIndex) {
int target = -nums[targetIndex];

int i = targetIndex + 1;
int j = nums.length - 1;
while (i < j) {
int twoSum = nums[i] + nums[j];

if (target > twoSum) {
i++;
}

if (target < twoSum) {
j--;
}

if (target == twoSum) {
result.add(List.of(-target, nums[i], nums[j]));
int current = nums[i];
while (i < nums.length - 2 && current == nums[i + 1]) {
i++;
}
i++;
}
}
}
```
29 changes: 29 additions & 0 deletions encode-and-decode-strings/dev-jonghoonpark.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
- 문제
- 유료 : https://leetcode.com/problems/encode-and-decode-strings/
- 무료 : https://www.lintcode.com/problem/659/
- time complexity : O(n)
- space complexity : O(n \* m), m은 각 문자열 길이의 평균
- 블로그 링크 : https://algorithm.jonghoonpark.com/2024/05/29/leetcode-271

```java
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for (String str : strs) {
sb.append(str.replace("%", "%25").replace(",", "%2C")).append(",");
}
return sb.length() > 0 ? sb.toString() : "";
}

public List<String> decode(String str) {
List<String> decodedList = new ArrayList<>();
if (str.length() > 0) {
int commaIndex = str.indexOf(",");
while (commaIndex > -1) {
decodedList.add(str.substring(0, commaIndex).replace("%2C", ",").replace("%25", "%"));
str = str.substring(commaIndex + 1);
commaIndex = str.indexOf(",");
}
}
return decodedList;
}
```
28 changes: 28 additions & 0 deletions longest-consecutive-sequence/dev-jonghoonpark.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
- 문제 : https://leetcode.com/problems/longest-consecutive-sequence/
- time complexity : O(n)
- space complexity : O(n)
- 블로그 링크 : https://algorithm.jonghoonpark.com/2024/05/28/leetcode-128

```java
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();

for(int num : nums) {
set.add(num);
}

int max = 0;
for(int num : set) {
if (!set.contains(num - 1)) {
int current = 1;
while (set.contains(num + 1)) {
current++;
num++;
}
max = Math.max(current, max);
}
}

return max;
}
```
75 changes: 75 additions & 0 deletions product-of-array-except-self/dev-jonghoonpark.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
- 문제 : https://leetcode.com/problems/product-of-array-except-self/
- time complexity : O(n)
- space complexity : O(n)
- 블로그 링크 : https://algorithm.jonghoonpark.com/2024/05/08/leetcode-238

## case 나눠서 풀기
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 이게 더 재밌는 방법 같은데요? ㅋㅋ

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

앗...! ㅋㅋ 주관적인 기준이였군요 ㅎㅎ

아래 풀이를 들었을 때 워낙 혁신이였어서 저는 재밌게 느꼈었네요...! ㅎㅎ


```java
public int[] productExceptSelf(int[] nums) {
int[] products = new int[nums.length];
int result = 1;
int zeroCount = 0;

int p = 0;
while (p < nums.length) {
if (nums[p] != 0) {
result *= nums[p];
} else {
zeroCount++;
if (zeroCount >= 2) {
Arrays.fill(products, 0);
return products;
}
}
p++;
}

if (zeroCount == 1) {
p = 0;
while (p < nums.length) {
if (nums[p] == 0) {
products[p] = result;
}
p++;
}
} else {
p = 0;
while (p < nums.length) {
products[p] = result / nums[p];
p++;
}
}

return products;
}
```

## 재밋는 방법으로 풀기 (prefixProd)

```java
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];

int[] prefixProd = new int[nums.length];
int[] suffixProd = new int[nums.length];

prefixProd[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
prefixProd[i] = prefixProd[i-1] * nums[i];
}

suffixProd[nums.length - 1] = nums[nums.length - 1];
for (int i = nums.length - 2; i > -1; i--) {
suffixProd[i] = suffixProd[i + 1] * nums[i];
}

result[0] = suffixProd[1];
result[nums.length - 1] = prefixProd[nums.length - 2];
for (int i = 1; i < nums.length - 1; i++) {
result[i] = prefixProd[i - 1] * suffixProd[i + 1];
}

return result;
}
```
24 changes: 24 additions & 0 deletions top-k-frequent-elements/dev-jonghoonpark.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
- 문제 : https://leetcode.com/problems/top-k-frequent-elements/
- time complexity : O(nlogn)
- space complexity : O(n)
- 블로그 링크 : https://algorithm.jonghoonpark.com/2024/04/18/leetcode-347

```java
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> counter = new HashMap<>();

Arrays.stream(nums)
.forEach(num -> {
counter.put(num, counter.getOrDefault(num, 0) + 1);
});

return Arrays.copyOfRange(counter.entrySet().stream()
.sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
.mapToInt(Map.Entry::getKey)
.toArray(), 0, k);
Comment on lines +15 to +18
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

자바 스크림 API 잘 쓰시네요!

}
```

## tc, sc 관련 그렇게 생각한 이유

빈도를 기준으로 map을 생성하기 때문에 n 보다 적은 경우가 대다수 이겠지만, 최악의 경우 n개의 map entry가 생성될 수 잇음.