diff --git a/house-robber/TonyKim9401.java b/house-robber/TonyKim9401.java new file mode 100644 index 000000000..6be1011df --- /dev/null +++ b/house-robber/TonyKim9401.java @@ -0,0 +1,21 @@ +// TC: O(n) +// always need to check every case +// SC: O(n) +// the length of the result int list is same with the length of the given nums int list +class Solution { + public int rob(int[] nums) { + int[] result = new int[nums.length]; + + if (nums.length < 2) return nums[0]; + if (nums.length < 3) return Math.max(nums[0], nums[1]); + + result[0] = nums[0]; + result[1] = Math.max(nums[0], nums[1]); + + for (int i = 2; i < nums.length; i++) { + result[i] = Math.max(result[i - 1], result[i - 2] + nums[i]); + } + + return result[nums.length-1]; + } +} diff --git a/lowest-common-ancestor-of-a-binary-search-tree/TonyKim9401.java b/lowest-common-ancestor-of-a-binary-search-tree/TonyKim9401.java new file mode 100644 index 000000000..da377becc --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-search-tree/TonyKim9401.java @@ -0,0 +1,13 @@ +// TC: O(h) +// h = the high of binary search tree +// SC: O(1) +// Doesn't require additional space +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (p.val < root.val && q.val < root.val) + return lowestCommonAncestor(root.left, p, q); + if (p.val > root.val && q.val > root.val) + return lowestCommonAncestor(root.right, p, q); + return root; + } +} diff --git a/meeting-rooms/TonyKim9401.java b/meeting-rooms/TonyKim9401.java new file mode 100644 index 000000000..341b94f85 --- /dev/null +++ b/meeting-rooms/TonyKim9401.java @@ -0,0 +1,17 @@ +// TC: O(n log n) +// list sort +// SC: O(n) +// list sort max use O(n) +public class Solution { + public boolean canAttendMeetings(List intervals) { + intervals.sort(Comparator.comparingInt(o -> o.start)); + + for (int i = 0; i < intervals.size() - 1; i++) { + Interval preInterval = intervals.get(i); + Interval postInterval = intervals.get(i+1); + + if (preInterval.end > postInterval.start) return false; + } + return true; + } +} diff --git a/non-overlapping-intervals/TonyKim9401.java b/non-overlapping-intervals/TonyKim9401.java new file mode 100644 index 000000000..11df1c2d1 --- /dev/null +++ b/non-overlapping-intervals/TonyKim9401.java @@ -0,0 +1,21 @@ +// TC: O(n log n) +// in order to order the given intervals array +// SC: O(1) +// only constant space necessary +class Solution { + public int eraseOverlapIntervals(int[][] intervals) { + Arrays.sort(intervals, (o1, o2) -> Integer.compare(o1[1], o2[1])); + + int output = 0; + int end = intervals[0][1]; + + for (int i = 1; i < intervals.length; i++) { + int[] currentInterval = intervals[i]; + + if (currentInterval[0] < end) output += 1; + else end = currentInterval[1]; + } + + return output; + } +}