先贴一下此题的代码(JAVA版本)
import java.util.*;
public class Main {
public static List<String> solution(int n, List<String> s, List<Integer> x) {
// 首先得把两个输入数组整合一下
Map<String,Integer> myMap = new HashMap<String,Integer>();
List<String> s2 = new ArrayList<String>();
List<Integer> x2 = new ArrayList<Integer>();
int j = 0;
for(int i = 0;i<s.size();i++){
if(myMap.containsKey(s.get(i))){
int idx = myMap.get(s.get(i));
x2.set(idx, x2.get(idx)+x.get(i));
}else{
s2.add(s.get(i));
x2.add(x.get(i));
myMap.put(s.get(i),j++);
}
}
// 创建一个列表来存储每个参与者的信息
List<Participant> participants = new ArrayList<>();
// 将每个参与者的名字和抢到的金额以及抢红包的顺序存入列表
for (int i = 0; i < s2.size(); i++) {
participants.add(new Participant(s2.get(i), x2.get(i), i));
}
// 根据题目要求进行排序
Collections.sort(participants, new Comparator<Participant>() {
@Override
public int compare(Participant p1, Participant p2) {
// 先按抢到的金额降序排序
if (p1.amount != p2.amount) {
return p2.amount - p1.amount;
}
// 如果金额相同,按抢红包的顺序升序排序
return p1.order - p2.order;
}
});
// 提取排序后的名字列表
List<String> result = new ArrayList<>();
for (Participant p : participants) {
result.add(p.name);
}
return result;
}
// 定义一个内部类来存储参与者的信息
static class Participant {
String name;
int amount;
int order;
public Participant(String name, int amount, int order) {
this.name = name;
this.amount = amount;
this.order = order;
}
}
public static void main(String[] args) {
System.out.println(solution(4, Arrays.asList("a", "b", "c", "d"), Arrays.asList(1, 2, 2, 1)).equals(Arrays.asList("b", "c", "a", "d")));
System.out.println(solution(3, Arrays.asList("x", "y", "z"), Arrays.asList(100, 200, 200)).equals(Arrays.asList("y", "z", "x")));
System.out.println(solution(5, Arrays.asList("m", "n", "o", "p", "q"), Arrays.asList(50, 50, 30, 30, 20)).equals(Arrays.asList("m", "n", "o", "p", "q")));
}
}
分析
在这个问题中,我们需要注意:每个人可以抢多个红包,这意味着需要对红包数据进行处理,尤其是涉及到抢红包的同学 ID 和金额的部分。具体的处理过程是首先利用 map 来存储每个抢红包同学的 ID 以及他们抢到的红包金额。每当同一个 ID 出现时,我们就需要将其之前的金额加上当前的红包金额,从而确保每个同学的红包金额是累加的。
处理完成之后,我们得到了两个新的列表:一个是每个同学抢到的红包金额,另一个是对应的同学 ID。接下来,是排序问题。我们首先根据红包金额进行降序排序,因为我们想要优先处理金额大的红包;接着,在金额相同的情况下,我们需要根据同学抢红包的时间进行升序排序。为了实现这个排序操作,我们可以构造一个结构体,在这个结构体中存储抢红包的同学 ID 以及他们抢到的红包总金额。
接着,我们可以重写结构体的排序函数,使得它首先按照红包金额进行降序排序;如果金额相同,则按同学的 ID 排序,确保抢红包时间越早的同学排在前面。这样,通过排序后,我们就能够得到一个按照金额优先、时间次之的最终结果。
下面这里是排序代码(AI写的学习一下)
// 根据题目要求进行排序
Collections.sort(participants, new Comparator<Participant>() {
@Override
public int compare(Participant p1, Participant p2) {
// 先按抢到的金额降序排序
if (p1.amount != p2.amount) {
return p2.amount - p1.amount;
}
// 如果金额相同,按抢红包的顺序升序排序
return p1.order - p2.order;
}
});
这种写法以后可以借鉴一下。