大意是,给一个数组costs代表n个英雄的价格,给一个coins代表拥有的钱,问最多可以买多少个英雄,将可以买到的英雄价格按照在原数组中的顺序返回。
例子
costs:[2,1,3,4,5]
coins:10
答案:[2,1,3,4]
求大佬帮忙看下我的为什么错了,只通过了66%的例子
题目并未给数据范围
public class Solution {
/**
* Note: 类名、方法名、参数名已经指定,请勿修改
*
*
* 根据价格列表和当前点券数,计算出能买到的最多英雄
* @param costs int整型 一维数组 英雄点券价格列表
* @param coins int整型 拥有的点券
* @return int整型一维数组
*/
public int[] solution(int[] costs, int coins) {
// write code here
int[] copy = Arrays.copyOf(costs, costs.length);
Arrays.sort(copy);
HashMap<Integer,Integer> hm=new HashMap<>();
int cost=0;
int count=0;
for (int i = 0; i <costs.length; i++) {
if(copy[i]+cost<=coins){
count++;
hm.merge(copy[i],1,Integer::sum);
cost=cost+copy[i];
}else {
break;
}
}
int[] res=new int[count];
int index=count-1;
for (int i = costs.length-1; i >=0; i--) {
if(hm.containsKey(costs[i])&&hm.get(costs[i])>0){
res[index]=costs[i];
hm.merge(costs[i],-1,Integer::sum);
index--;
}
}
return res;
}
}我以为是cost是int类型超出范围了,结果改成long类型还是只通过66%