Skip to content
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

[TONY] WEEK 06 Solutions #465

Merged
merged 5 commits into from
Sep 21, 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
24 changes: 24 additions & 0 deletions container-with-most-water/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// TC:
// SC:
Comment on lines +1 to +2
Copy link
Contributor

Choose a reason for hiding this comment

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

TC, SC 써주시면 더 좋을 것 같습니다~!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

헉..
TC: O(n) -> 최대 모든 배열의 값을 한번씩 확인해야함
SC: O(1) -> 상수 공간만 사용
으로 봐주시면 감사하겠습니다..!

class Solution {
public int maxArea(int[] height) {
int max = 0;

int start = 0;
int end = height.length-1;

while (start < end) {
int heightLeft = height[start];
int heightRight = height[end];

int hei = Math.min(heightLeft, heightRight);
int wid = end - start;

max = Math.max(max, hei*wid);

if (heightRight > heightLeft) start += 1;
else end -= 1;
}
return max;
}
}
56 changes: 56 additions & 0 deletions design-add-and-search-words-data-structure/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// SC: O(n)
// -> n is the length of the given String
// TC: O(n * 26)
// -> n is the length of the given String * the number of alphabets
Comment on lines +1 to +4
Copy link
Contributor

Choose a reason for hiding this comment

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

이건 제 의견인데, Big O 분석은 각 함수에 대해 각각 진행하는 것이 더 좋을 것 같습니다

Tony님은 어떻게 생각하세요? :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

앗 넵! 저도 각 함수에 대해 각각 진행하는게 좋을것 같습니다. 왜 이렇게 했는지 모르겟네요.. 의견 감사합니다!

class TrieNode {
TrieNode[] childNode;
boolean isEndOfWord;

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

class WordDictionary {

private TrieNode root;

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

public void addWord(String word) {
TrieNode node = root;

for (char c : word.toCharArray()) {
int idx = c - 'a';
if (node.childNode[idx] == null) {
node.childNode[idx] = new TrieNode();
}
node = node.childNode[idx];
}
node.isEndOfWord = true;
}

public boolean search(String word) {
return searchInNode(word.toCharArray(), 0, root);
}

private boolean searchInNode(char[] word, int idx, TrieNode node) {
if (idx == word.length) return node.isEndOfWord;

char c = word[idx];

if (c == '.') {
for (TrieNode child : node.childNode) {
if (child != null && searchInNode(word, idx+1, child)) return true;
}
return false;
} else {
int childIdx = c - 'a';
if (node.childNode[childIdx] == null) return false;
return searchInNode(word, idx+1, node.childNode[childIdx]);
}
}
}
22 changes: 22 additions & 0 deletions longest-increasing-subsequence/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// TC: O(n log n)
// -> nums for loop O(n) + binarySearch O(log n)
// SC: O(n)
// -> ArrayList could have nums all elements
class Solution {
public int lengthOfLIS(int[] nums) {
List<Integer> output = new ArrayList<>();

for (int num : nums) {
int start = 0;
int end = output.size();
while (start < end) {
int mid = start + (end - start) / 2;
if (output.get(mid) < num) start = mid + 1;
else end = mid;
}
if (start == output.size()) output.add(num);
else output.set(start, num);
}
return output.size();
}
}
44 changes: 44 additions & 0 deletions spiral-matrix/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> output = new ArrayList<>();
int north = 0;
int south = matrix.length - 1;
int east = matrix[0].length - 1;
int west = 0;

while (north <= south && west <= east) {
int j = west;
while (j <= east) {
output.add(matrix[north][j]);
j += 1;
}
north += 1;

int i = north;
while (i <= south) {
output.add(matrix[i][east]);
i += 1;
}
east -= 1;

if (north <= south) {
j = east;
while (j >= west) {
output.add(matrix[south][j]);
j -= 1;
}
south -= 1;
}

if (west <= east) {
i = south;
while (i >= north) {
output.add(matrix[i][west]);
i -= 1;
}
west += 1;
}
}
return output;
}
}
18 changes: 18 additions & 0 deletions valid-parentheses/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// TC: O(n)
// -> n = s.length
// SC: O(n)
// -> n = s.length / 2
Comment on lines +3 to +4
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
Contributor Author

Choose a reason for hiding this comment

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

stack에 데이터가 들어가는 경우는 현재 값이 (, {, [ 인 경우 뿐이고, 최악의 경우(((({{{[[[ 같은 값이 주어지더라도, 여전히 상수값이기에 공간 복잡도는 O(n)이라고 생각합니다!

Copy link
Contributor

@obzva obzva Sep 19, 2024

Choose a reason for hiding this comment

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

답변 감사합니다 토니님 :)

O(N)의 형태로 사용 공간이 증가한다는 것은 이해 및 동의합니다

여전히 제가 이해를 하지 못한 부분이 있어서 더 질문 드리고 싶습니다

  1. n = s.length / 2 이 부분에 대해서 더 자세히 설명 부탁 드려도 될까요?

  2. 최악의 경우(((({{{[[[ 같은 값이 주어지더라도, 여전히 상수값에서 상수값이라는 표현에 대해 잘 이해하지 못했습니다. 1 <= s.length <= 10^4이라는 입력값 제한 조건이 있는데, 이 중에서 10^4를 상수라고 표현하신 걸까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@obzva 스택은 열린 괄호가 들어올 때마다 저장되고 닫힌 괄호가 들어올 때 제거되므로, 스택의 최대 크기는 열린 괄호의 개수만큼이 될겁니다. 따라서, 공간 복잡도는 최악의 경우 O( s.length() / 2) 라고 생각되지만 공간 복잡도계산시 보통 상수를 무시하므로 O(n) 이라고 생각합니다.

Copy link
Contributor

Choose a reason for hiding this comment

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

아하 감사합니다 ㅎㅎㅎ
그치만 s 자체가 ((((((((((((((((((((((((((((((같은 값이 주어진다면 최악의 경우엔 공간 사용량이 s.length() / 2가 아닌 s.length() 아닌가요? 결국 아무 char도 pop되지 않고 스택에 쌓이기만 할테니까요

class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();

for (char c : s.toCharArray()) {
if (c == '(') stack.add(')');
else if (c == '{') stack.add('}');
else if (c == '[') stack.add(']');
else if (stack.isEmpty() || stack.pop() != c) return false;
}

return stack.isEmpty();
}
}