目录
题目
输入一个按升序排序的整数数组(可能包含重复数字),你需要将它们分割成几个子序列,其中每个子序列至少包含三个连续整数。返回你是否能做出这样的分割?
示例 1:
输入: [1,2,3,3,4,5]
输出: True
解释:
你可以分割出这样两个连续子序列 :
1, 2, 3
3, 4, 5
示例 2:
输入: [1,2,3,3,4,4,5,5]
输出: True
解释:
你可以分割出这样两个连续子序列 :
1, 2, 3, 4, 5
3, 4, 5
示例 3:
输入: [1,2,3,4,4,5]
输出: False
提示:
输入的数组长度范围为 [1, 10000]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/split-array-into-consecutive-subsequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
运行时间
代码
class Solution { public boolean isPossible(int[] nums) { int length=nums.length; if((length<3)) { return false; } HashMap<Integer,Integer> count=new HashMap<>(); //统计某个数的次数 HashMap<Integer,Integer> end=new HashMap<>();//统计某个数结尾(长度大于等于3)的次数 for(int i=0;i<length;i++) { count.put(nums[i], count.getOrDefault(nums[i],0)+1); } for(int i=0;i<length;i++) { //System.out.println("dd"); if(count.get(nums[i])==0)//发现这个数已经没了,继续循环 continue; else if(end.containsKey(nums[i]-1)&&end.get(nums[i]-1)>0){//发现有以比该数小一结尾的窜,则就把该数字加在上面 end.put(nums[i]-1, end.get(nums[i]-1)-1); end.put(nums[i],end.getOrDefault(nums[i], 0)+1); count.put(nums[i], count.get(nums[i])-1); }else if(count.containsKey(nums[i]+1)&&count.get(nums[i]+1)>0&&count.containsKey(nums[i]+2)&&count.get(nums[i]+2)>0){//发现有以该数开始连续的3个数,符合题意 end.put(nums[i]+2,end.getOrDefault(nums[i]+2, 0)+1); count.put(nums[i], count.get(nums[i])-1); count.put(nums[i]+1, count.get(nums[i]+1)-1); count.put(nums[i]+2, count.get(nums[i]+2)-1); }else { return false; } } return true; } }