659. Split Array into Consecutive Subsequences!
class Solution {
public boolean isPossible(int[] nums) {
// deal with the number depending on conditions
// record the frequency of num in nums
Map<Integer, Integer> freq = new HashMap<>();
Map<Integer, Integer> need = new HashMap<>();
for(int num : nums) freq.put(num, freq.getOrDefault(num, 0)+1);
for(int num : nums){
if(freq.get(num)==0) continue;
//first check if the num can be append to existing subsequence,
//if not, then check if num can form a subsequence,
//start from num
if(need.containsKey(num) && need.get(num) >0){
need.put(num, need.get(num)-1);
freq.put(num, freq.get(num)-1);
need.put(num+1, need.getOrDefault(num+1,0)+1);
}else if(freq.getOrDefault(num, 0)>0
&& freq.getOrDefault(num+1, 0)>0
&& freq.getOrDefault(num+2, 0)>0){
freq.put(num, freq.get(num)-1);
freq.put(num+1, freq.get(num+1)-1);
freq.put(num+2, freq.get(num+2)-1);
need.put(num+3, need.getOrDefault(num+3,0)+1);
}else{
return false;
}
}
return true;
}
}
Last updated
Was this helpful?