From f9de13b76ae1784259eaf100d43f89e3ae8a2529 Mon Sep 17 00:00:00 2001 From: yennanliu Date: Tue, 17 Sep 2024 21:22:19 +0800 Subject: [PATCH] update 659 java --- .../SplitArrayIntoConsecutiveSubsequences.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/leetcode_java/src/main/java/LeetCodeJava/Greedy/SplitArrayIntoConsecutiveSubsequences.java b/leetcode_java/src/main/java/LeetCodeJava/Greedy/SplitArrayIntoConsecutiveSubsequences.java index b399ce7e..19c80981 100644 --- a/leetcode_java/src/main/java/LeetCodeJava/Greedy/SplitArrayIntoConsecutiveSubsequences.java +++ b/leetcode_java/src/main/java/LeetCodeJava/Greedy/SplitArrayIntoConsecutiveSubsequences.java @@ -289,7 +289,7 @@ public boolean isPossible_5(int[] nums) { * -> key is the "last element" of subsequences * -> value is the length of subsequences end with that key */ - Map>lastElements = new HashMap<>(); + Map> lastElements = new HashMap<>(); // The loop processes each element in the nums array to update the lastElements map. for (int element: nums){ /** @@ -305,7 +305,9 @@ public boolean isPossible_5(int[] nums) { int subseqCount = 0; if (lastElements.containsKey(element-1)){ subseqCount = lastElements.get(element-1).poll(); - if (lastElements.get(element-1).isEmpty()) lastElements.remove(element-1); + if (lastElements.get(element-1).isEmpty()){ + lastElements.remove(element-1); + } } // The lastElements map is updated to include or update the entry for the current element, // Adding a new subsequence of length subseqCount + 1. @@ -317,8 +319,13 @@ public boolean isPossible_5(int[] nums) { * - subseqCount + 1 indicates that the current subsequence is being extended by 1, because the element has been added to the subsequence. * - add() adds this updated subsequence length * (i.e., subseqCount + 1) to the PriorityQueue associated with the element. + * */ - lastElements.get(element).add(subseqCount+1); + // below code are equivalent to each other + //lastElements.get(element).add(subseqCount+1); + PriorityQueue pq = lastElements.getOrDefault(element, new PriorityQueue<>()); + pq.add(subseqCount + 1); + lastElements.put(element, pq); } for (Map.Entry>entry: lastElements.entrySet()){ /**