Skip to content

[TONY] WEEK 5 Solution #451

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 6 commits into from
Sep 13, 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
30 changes: 30 additions & 0 deletions 3sum/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// TC: O(n^2)
// SC: O(n)
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {

Arrays.sort(nums);

List<List<Integer>> output = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();

for (int i = 0; i < nums.length; ++i) map.put(nums[i], i);

for (int i = 0; i < nums.length - 2; ++i) {
if (nums[i] > 0) break;

for (int j = i + 1; j < nums.length - 1; ++j) {
int cValue = -1 * (nums[i] + nums[j]);

if (map.containsKey(cValue) && map.get(cValue) > j) {
output.add(List.of(nums[i], nums[j], cValue));
}
j = map.get(nums[j]);
}

i = map.get(nums[i]);
}

return output;
}
}
16 changes: 16 additions & 0 deletions best-time-to-buy-and-sell-stock/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// TC: O(n)
// SC: O(1)
class Solution {
public int maxProfit(int[] prices) {
int bestProfit = 0;
int buyPrice = prices[0];
for (int i = 1; i < prices.length; i++) {
if (buyPrice > prices[i]) {
buyPrice = prices[i];
continue;
}
bestProfit = Math.max(bestProfit, prices[i] - buyPrice);
}
return bestProfit;
}
}
25 changes: 25 additions & 0 deletions group-anagrams/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// TC: O(n * m log m)
// SC: O(n * m)
Copy link
Contributor

Choose a reason for hiding this comment

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

질문

mstrs 배열 내 원소의 평균~최대 크기라고 보면 될까요?

Copy link
Contributor Author

@TonyKim9401 TonyKim9401 Sep 13, 2024

Choose a reason for hiding this comment

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

아뇨! 제 풀이 방식에서는 map을 사용하고 있고
Key: String, Value: List<String> 을 사용하고 있습니다.
즉 n개의 key 값들에 m개의 value가 공간을 차지하는걸 최대로 보고 n * m 으로 공간 복잡도를 구했습니다!

class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> output = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();

for (int i = 0; i < strs.length; i++) {
char[] charArray = strs[i].toCharArray();
Arrays.sort(charArray);
Copy link
Contributor

Choose a reason for hiding this comment

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

찾아보니 JAVA의 Arrays.sort method도 퀵소트를 사용하는 것 같은데, 이 부분에 대한 계산이 누락된 것 같아 보입니다

Copy link
Contributor Author

Choose a reason for hiding this comment

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

앗 감사합니다!
주어진 문자열 n에서 각 요소를 m으로 두고 sort하면 Java에서는 m log m 시간이 걸립니다.
따라서 시간 복잡도가 O(n * m log m)을 가지게 되겠네요.
통찰력 감탄합니다 감사합니다!! 💯

String target = new String(charArray);

if (map.containsKey(target)) {
map.get(target).add(strs[i]);
} else {
List<String> inside = new ArrayList<>();
inside.add(strs[i]);
map.put(target, inside);
}
}

for (String key : map.keySet()) output.add(map.get(key));
return output;
}
}
56 changes: 56 additions & 0 deletions implement-trie-prefix-tree/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
class TrieNode {
TrieNode[] children;
boolean isEndOfWord;

public TrieNode() {
children = new TrieNode[26];
isEndOfWord = false;
}
}

class Trie {

private TrieNode root;

public Trie() {
root = new TrieNode();
}

// TC: O(n)
// SC: O(n * m)
// -> word length * new TrieNode spaces
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null) {
node.children[idx] = new TrieNode();
}
node = node.children[idx];
}
node.isEndOfWord = true;
}

// TC: O(n)
// SC: O(1)
public boolean search(String word) {
TrieNode node = searchPrefix(word);
return node != null && node.isEndOfWord;
}

// TC: O(n)
// SC: O(1)
private TrieNode searchPrefix(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null) return null;
node = node.children[idx];
}
return node;
}

public boolean startsWith(String prefix) {
return searchPrefix(prefix) != null;
}
}
22 changes: 22 additions & 0 deletions word-break/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// TC: O(n^2)
// -> use 2 for-loops to search
Comment on lines +1 to +2
Copy link
Member

Choose a reason for hiding this comment

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

@TonyKim9401 입력 값이 두 개 이상일 때는 n이 무엇을 의미하는지 명시해주시는 것이 좋을 것 같습니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

다음부터는 명시 하도록 하겠습니다!

// SC: O(n)
// -> boolean array's size
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> set = new HashSet(wordDict);

boolean[] dp = new boolean[s.length() + 1];
Copy link
Contributor

Choose a reason for hiding this comment

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

dp 배열을 어떻게 정의하셨는지 설명을 적어주시면 리뷰하기 좀 더 수월할 것 같습니다 감사합니다 :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

""의 경우 항상 true이므로 0을 true로 두고, 배열의 마지막이 true이면 모든 문자가 존재한다는 판단으로
주어진 문자열의 길이 + 1 으로 정의해 보았습니다!

dp[0] = true;

for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
Copy link
Contributor

Choose a reason for hiding this comment

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

1 <= s.length <= 300
1 <= wordDict.length <= 1000

s의 모든 substring을 조회하는 것이 wordDict를 조회하는 것보다 더 빠르겠군요..?

입력 조건을 더 잘 봐야겠다는 생각이 듭니다 감사합니다 :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

저도 리팩토링 하면서 발견한거라 처음에 wordDict 조회하는걸로 풀었습니다 ㅎㅎ
코드 리뷰 감사합니다!

if (dp[j] && set.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}