diff --git a/container-with-most-water/YuuuuuuYu.java b/container-with-most-water/YuuuuuuYu.java new file mode 100644 index 000000000..5be822bab --- /dev/null +++ b/container-with-most-water/YuuuuuuYu.java @@ -0,0 +1,40 @@ +/** + * Runtime: 3ms + * Time Complexity: O(n) + * + * Memory: 77.24MB + * Space Complexity: O(1) + * + * Approach: 좌우 높이 중 더 작은 높이 기준으로 계산하기 때문에 그 높이를 최대한 높일 수 있는 방향으로 포인터 이동 + * - while문 내에서 현재 포인터의 높이보다 같거나 작은 높이를 건너뛰도록 최적화 + */ +class Solution { + public int maxArea(int[] height) { + int left = 0; + int right = height.length-1; + int max = 0; + + while (left < right) { + int hLeft = height[left]; + int hRight = height[right]; + int currentArea = (right-left) * Math.min(hLeft, hRight); + if (currentArea > max) { + max = currentArea; + } + + if (hLeft < hRight) { + left++; + while (left < right && height[left] <= hLeft) { + left++; + } + } else { + right--; + while (left < right && height[right] <= hRight) { + right--; + } + } + } + + return max; + } +} diff --git a/longest-increasing-subsequence/YuuuuuuYu.java b/longest-increasing-subsequence/YuuuuuuYu.java new file mode 100644 index 000000000..853218d91 --- /dev/null +++ b/longest-increasing-subsequence/YuuuuuuYu.java @@ -0,0 +1,40 @@ +/** + * Runtime: 3ms + * Time Complexity: O(n log n) + * - 각 요소마다 이분 탐색 + * + * Memory: 45.99MB + * Space Complexity: O(n) + * + * Approach: Patience Sorting, 각 원소를 순서대로 확인하며 현재까지 만든 가장 유리한 수열 계산 + * - result의 모든 원소보다 크면 맨 뒤에 추가 + * - 그렇지 않으면, 이분 탐색으로 나온 위치에 값을 대체 + */ +class Solution { + public int lengthOfLIS(int[] nums) { + int[] result = new int[nums.length]; + int resultSize = 0; + + for (int num : nums) { + int left = 0; + int right = resultSize; + + while (left < right) { + int mid = left + (right-left) / 2; + if (result[mid] < num) { + left = mid+1; + } else { + right = mid; + } + } + + result[left] = num; + + if (left == resultSize) { + resultSize++; + } + } + + return resultSize; + } +} diff --git a/valid-parentheses/YuuuuuuYu.java b/valid-parentheses/YuuuuuuYu.java new file mode 100644 index 000000000..3021f1ede --- /dev/null +++ b/valid-parentheses/YuuuuuuYu.java @@ -0,0 +1,33 @@ +/** + * Runtime: 4ms + * Time Complexity: O(n) + * + * Memory: 42.94MB + * Space Complexity: O(n) + * + * Approach: 스택 사용 + * - 열린 괄호를 푸시하면서 닫힌 괄호가 나올 때마다 스택에서 팝하여 짝이 맞는지 확인 + */ +class Solution { + public boolean isValid(String s) { + if (s.length()%2 == 1) return false; + + Stack stack = new Stack<>(); + Map map = new HashMap<>(); + map.put('(', ')'); + map.put('{', '}'); + map.put('[', ']'); + + for (char ch: s.toCharArray()) { + if (map.containsKey(ch)) { + stack.push(ch); + } else if (")}]".indexOf(ch) != -1) { + if (stack.isEmpty() || ch != map.get(stack.pop())) { + return false; + } + } + } + + return stack.isEmpty(); + } +}