From db5c31411272b4a7140842d11ee79f5560dbe328 Mon Sep 17 00:00:00 2001 From: dongha kim Date: Sat, 14 Dec 2024 14:08:01 +0900 Subject: [PATCH] =?UTF-8?q?fix=20:=20=EC=BD=94=EB=93=9C=20=EC=9B=90?= =?UTF-8?q?=EB=B3=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- house-robber/imsosleepy.java | 21 ++++++-- longest-consecutive-sequence/imsosleepy.java | 51 +++++++++++++++++++- 2 files changed, 67 insertions(+), 5 deletions(-) diff --git a/house-robber/imsosleepy.java b/house-robber/imsosleepy.java index 488f282df..aaff2084e 100644 --- a/house-robber/imsosleepy.java +++ b/house-robber/imsosleepy.java @@ -1,6 +1,3 @@ -// 점화식의 최대값을 구하는 방법 -// 1. 현재 위치의 최대 값은 한칸 전 집까지만 털었던가(두칸 연속 겹치면 안된다는 룰을 지키면서) -// 2. 두칸 전 집까지 털고 + 현재집을 털었을 때다 // 공간복잡도를 줄이는법. 배열로 관리 안하기 class Solution { public int rob(int[] nums) { @@ -16,3 +13,21 @@ public int rob(int[] nums) { return prev1; } } + +// 점화식의 최대값을 구하는 방법 +// 1. 현재 위치의 최대 값은 한칸 전 집까지만 털었던가(두칸 연속 겹치면 안된다는 룰을 지키면서) +// 2. 두칸 전 집까지 털고 + 현재집을 털었을 때다 +class Solution { + public int rob(int[] nums) { + if (nums.length == 1) { + return nums[0]; + } + int[] dp = new int[nums.length]; + dp[0] = nums[0]; + dp[1] = Math.max(nums[0], nums[1]); + for (int i = 2; i < nums.length; i++) { + dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]); + } + return dp[nums.length - 1]; + } +} diff --git a/longest-consecutive-sequence/imsosleepy.java b/longest-consecutive-sequence/imsosleepy.java index c59da0b98..e9a2d540b 100644 --- a/longest-consecutive-sequence/imsosleepy.java +++ b/longest-consecutive-sequence/imsosleepy.java @@ -1,5 +1,3 @@ -// 이중 변환 필요 없음 -// 정렬이 들어가면 O(nlogn) 아래로 줄일 수 없음 // 중복여부만 제거하고 포함여부로 판단 O(N) class Solution { public int longestConsecutive(int[] nums) { @@ -30,3 +28,52 @@ public int longestConsecutive(int[] nums) { return maxLength; } } +// 정렬이 들어가면 O(nlogn) 아래로 줄일 수 없음 +class Solution { + public int longestConsecutive(int[] nums) { + if(nums.length == 0) return 0; + TreeSet set = new TreeSet<>(); + for (int num : nums) { + set.add(num); + } + int max = 1; + int consecutiveCount = 1; + int prev = set.pollFirst(); + while(!set.isEmpty()) { + int next = set.pollFirst(); + if (next - prev == 1) { + consecutiveCount++; + } else { + max = Math.max(consecutiveCount, max); + consecutiveCount = 1; + } + prev = next; + } + return Math.max(max, consecutiveCount); + } +} +// 이중 변환 필요 없음 +class Solution { + public int longestConsecutive(int[] nums) { + if(nums.length == 0) return 0; + HashSet set = new HashSet<>(); + for (int num : nums) { + set.add(num); + } + PriorityQueue pq = new PriorityQueue<>(set); + int max = 1; + int consecutiveCount = 1; + int prev = pq.poll(); + while(!pq.isEmpty()) { + int next = pq.poll(); + if (next - prev == 1) { + consecutiveCount++; + } else { + max = Math.max(consecutiveCount, max); + consecutiveCount = 1; + } + prev = next; + } + return Math.max(max, consecutiveCount); + } +}