在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ You are given an integer array sorted in ascending order (may contain duplicates), you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split. Example 1: Input: [1,2,3,3,4,5] Output: True Explanation: You can split them into two consecutive subsequences : 1, 2, 3 3, 4, 5 Example 2: Input: [1,2,3,3,4,4,5,5] Output: True Explanation: You can split them into two consecutive subsequences : 1, 2, 3, 4, 5 3, 4, 5 Example 3: Input: [1,2,3,4,4,5] Output: False Note:
输入一个按升序排序的整数数组(可能包含重复数字),你需要将它们分割成几个子序列,其中每个子序列至少包含三个连续整数。返回你是否能做出这样的分割? 示例 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 提示:
620ms 1 class Solution { 2 func isPossible(_ nums: [Int]) -> Bool { 3 var pre = 0 4 var preCount = 0 5 var starts = [Int]() 6 var anchor = 0 7 for i in 0..<nums.count { 8 let t = nums[i] 9 if i == nums.count - 1 || nums[i+1] != t { 10 let count = i - anchor + 1 11 if pre != 0 && (t - pre) != 1 { 12 while preCount > 0 { 13 if pre < (2 + starts.removeFirst()) { 14 return false 15 } 16 preCount -= 1 17 } 18 pre = 0 19 } 20 21 if pre == 0 || (t - pre) == 1{ 22 while preCount > count { 23 preCount -= 1 24 if (t-1) < (2 + starts.removeFirst()) { 25 return false 26 } 27 } 28 29 while preCount < count { 30 starts.append(t) 31 preCount += 1 32 } 33 } 34 35 pre = t 36 preCount = count 37 anchor = i+1 38 } 39 } 40 41 while preCount > 0 { 42 if nums[nums.count - 1] < (2 + starts.removeFirst()) { 43 return false 44 } 45 preCount -= 1 46 } 47 return true 48 } 49 } Runtime: 712 ms
Memory Usage: 19.4 MB
1 class Solution { 2 func isPossible(_ nums: [Int]) -> Bool { 3 var freq:[Int:Int] = [Int:Int]() 4 var need:[Int:Int] = [Int:Int]() 5 for num in nums 6 { 7 freq[num,default:0] += 1 8 } 9 for num in nums 10 { 11 if freq[num,default:0] == 0 12 { 13 continue 14 } 15 else if need[num,default:0] > 0 16 { 17 need[num,default:0] -= 1 18 need[num + 1,default:0] += 1 19 } 20 else if freq[num + 1,default:0] > 0 && freq[num + 2,default:0] > 0 21 { 22 freq[num + 1,default:0] -= 1 23 freq[num + 2,default:0] -= 1 24 need[num + 3,default:0] += 1 25 } 26 else 27 { 28 return false 29 } 30 freq[num,default:0] -= 1 31 } 32 return true 33 } 34 }
|
请发表评论