数组越界之谜:优化计数排序解决最后一块石头问题

内容概览
在尝试解决“最后一块石头”的问题时,采用计数排序算法,却遭遇数组越界错误。通过调整数组大小,问题得以解决。本文深入探讨错误原因及优化方案。
英雄哪里出来
2024-11-11 10:45
赞1评论3
Ga.难搞啊 提问:英雄歌,这个是计数排序,最后一块石头,但是一直会报错数组越界(a[nums[i]]++) : void jishuSort(int* nums,int numsSize){ int a[31] = {0}; for(int i = 0;i < numsSize;i++){ a[nums[i]]++;//先把所有元素给了哈希 } int n = numsSize; int index = 0; for(int i = 0;i<n;i++){ while(a[i]){ nums[index++] = i;//再把顺序的返回给原数组 a[i]--; } } } int lastStoneWeight(int* stones, int stonesSize) { jishuSort(stones,stonesSize); int n = stonesSize; while(n>1){ if(stones[n-1]==stones[n-2]){ stones[n-1] = 0; stones[n-2] = 0; n-=2; } else{ stones[n-2] = stones[n-1] - stones[n-2]; stones[n-1] = 0; n -= 1; } jishuSort(stones,n); } return stones[0]; }
int a[31] = {0}; 数组开小了,开到 1001...

英雄算法联盟

星球已运营 4 年零 211 天

累计超过  5700+  位成员加入

18小时前

最近更新

51000+

内容数

进入星球主页