LeetCode //C - 1296. Divide Array in Sets of K Consecutive Numbers

发布时间:2026/10/19 15:33:03
LeetCode //C - 1296. Divide Array in Sets of K Consecutive Numbers 1296. Divide Array in Sets of K Consecutive NumbersGiven 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.Return true if it is possible. Otherwise, return false.Example 1:Input:nums [1,2,3,3,4,4,5,6], k 4Output:trueExplanation:Array can be divided into [1,2,3,4] and [3,4,5,6].Example 2:Input:nums [3,2,1,2,3,4,3,4,5,9,10,11], k 3Output:trueExplanation:Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].Example 3:Input:nums [1,2,3,4], k 3Output:falseExplanation:Each array should be divided in subarrays of size 3.Constraints:1 k n u m s . l e n g t h 10 5 1 k nums.length 10^51knums.length1051 n u m s [ i ] 10 9 1 nums[i] 10^91nums[i]109From: LeetCodeLink: 1296. Divide Array in Sets of K Consecutive NumbersSolution:Ideas:Sort the array, then repeatedly start groups from the smallest number that still has remaining occurrences.Code:#includestdbool.h#includestdlib.htypedefstruct{intkey;intcount;bool used;}HashEntry;staticintcompare(constvoid*a,constvoid*b){intx*(constint*)a;inty*(constint*)b;return(xy)-(xy);}staticunsignedinthashValue(intkey,intsize){return((unsignedint)key*2654435761u)%size;}staticHashEntry*findEntry(HashEntry*table,intsize,intkey){unsignedintindexhashValue(key,size);while(table[index].usedtable[index].key!key){index(index1)%size;}returntable[index];}boolisPossibleDivide(int*nums,intnumsSize,intk){if(numsSize%k!0){returnfalse;}qsort(nums,numsSize,sizeof(int),compare);inttableSizenumsSize*31;HashEntry*tablecalloc(tableSize,sizeof(HashEntry));if(tableNULL){returnfalse;}/* Count each number. */for(inti0;inumsSize;i){HashEntry*entryfindEntry(table,tableSize,nums[i]);if(!entry-used){entry-usedtrue;entry-keynums[i];}entry-count;}for(inti0;inumsSize;i){HashEntry*startEntryfindEntry(table,tableSize,nums[i]);intgroupsstartEntry-count;if(groups0){continue;}/* Form groups sets beginning with nums[i]. */for(intj0;jk;j){HashEntry*entryfindEntry(table,tableSize,nums[i]j);if(!entry-used||entry-countgroups){free(table);returnfalse;}entry-count-groups;}}free(table);returntrue;}

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询