|
| 1 | +# [1296. Divide Array in Sets of K Consecutive Numbers](https://leetcode-cn.com/problems/divide-array-in-sets-of-k-consecutive-numbers/) |
| 2 | + |
| 3 | +## 题目 |
| 4 | + |
| 5 | +Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers. |
| 6 | + |
| 7 | +Return true if it is possible. Otherwise, return false. |
| 8 | + |
| 9 | +**Example 1**: |
| 10 | + |
| 11 | + Input: nums = [1,2,3,3,4,4,5,6], k = 4 |
| 12 | + Output: true |
| 13 | + Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6]. |
| 14 | + |
| 15 | +**Example 2**: |
| 16 | + |
| 17 | + Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3 |
| 18 | + Output: true |
| 19 | + Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11]. |
| 20 | + |
| 21 | +**Example 3**: |
| 22 | + |
| 23 | + Input: nums = [1,2,3,4], k = 3 |
| 24 | + Output: false |
| 25 | + Explanation: Each array should be divided in subarrays of size 3. |
| 26 | + |
| 27 | +**Constraints:** |
| 28 | + |
| 29 | +- 1 <= k <= nums.length <= 100000 |
| 30 | +- 1 <= nums[i] <= 1000000000 |
| 31 | + |
| 32 | +## 题目大意 |
| 33 | + |
| 34 | +给你一个整数数组 nums 和一个正整数 k,请你判断是否可以把这个数组划分成一些由 k 个连续数字组成的集合。 |
| 35 | +如果可以,请返回 true;否则,返回 false。 |
| 36 | + |
| 37 | +## 解题思路 |
| 38 | + |
| 39 | +贪心算法 |
| 40 | + |
| 41 | +- 对nums升序排序 |
| 42 | +- 对nums内数字进行哈希计数(key:数字,value:数量) |
| 43 | +- 遍历nums中的数字,以数量大于1的数字作为连续数字开头,寻找连续数字后续元素,若无法找到 k 个连续数字则返回false |
| 44 | +- 所有数字都能找到 k 个连续数字返回true |
| 45 | + |
| 46 | +##代码 |
| 47 | + |
| 48 | +```go |
| 49 | +package leetcode |
| 50 | + |
| 51 | +import "sort" |
| 52 | + |
| 53 | +func isPossibleDivide(nums []int, k int) bool { |
| 54 | + mp := make(map[int]int) |
| 55 | + for _, v := range nums { |
| 56 | + mp[v] += 1 |
| 57 | + } |
| 58 | + sort.Ints(nums) |
| 59 | + for _, num := range nums { |
| 60 | + if mp[num] == 0 { |
| 61 | + continue |
| 62 | + } |
| 63 | + for diff := 0; diff < k; diff++ { |
| 64 | + if mp[num+diff] == 0 { |
| 65 | + return false |
| 66 | + } |
| 67 | + mp[num+diff] -= 1 |
| 68 | + } |
| 69 | + } |
| 70 | + return true |
| 71 | +} |
| 72 | +``` |
0 commit comments