gpt4 book ai didi

java - 向 ArrayList 添加元素失败

转载 作者:行者123 更新时间:2023-12-02 09:31:26 24 4
gpt4 key购买 nike

我正在研究这个 leetcode problem .

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// Employee info
class Employee {
// It's the unique id of each node;
// unique id of this employee
public int id;
// the importance value of this employee
public int importance;
// the id of direct subordinates
public List<Integer> subordinates;
};

class Solution {
public int getImportance(List<Employee> employees, int id) {
Map<Integer, Integer> values = new HashMap<>();
Map<Integer, List<Integer>> subordinates = new HashMap<>();

// put value and subordinates into maps
for(Employee employee : employees) {
int e_id = employee.id;
int value = employee.importance;
List<Integer> subordinate = employee.subordinates;
values.put(id, value);
subordinates.put(id, subordinate);
}

// find suborinates and add up the values
List<Integer> subs = subordinates.getOrDefault(id, new ArrayList<Integer>());
int total_value = values.getOrDefault(id, 0);

for(int sub_id : subs){
total_value = total_value + values.getOrDefault(sub_id, 0);
}

return total_value;
}
}
public class Sixninezero {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Employee e1 = new Employee();
e1.id = 3;
e1.importance = 3;
List<Integer> list_e1 = new ArrayList<>();
e1.subordinates = list_e1;

Employee e2 = new Employee();
e2.id = 2;
e2.importance = 5;
List<Integer> list_e2 = new ArrayList<>();
list_e2.add(3);
e2.subordinates = list_e2;

List<Employee> employees = new ArrayList<>();
employees.add(e1);
employees.add(e2);

Solution solution = new Solution();
int result = solution.getImportance(employees, 2);
System.out.println(result);
}

}

我创建了两个 Employee 对象并将它们添加到名为 employees 的 ArrayList 中,然后我通过了employeesgetImportance()方法。在此方法中,for 循环将遍历 employees并输入 id以及相应的value(importance)配对进入名为 values 的 map ,并执行类似于 subordinates 的操作 map 。所以每个valuessubordinates应该有 2 个元素,因为 employees有两个对象。但它总是有一个元素(第二个)。我认为 for 循环 ArrayList 时我做对了,代码有什么问题吗?

最佳答案

每次循环时,您都将方法参数中的 id 放入 values 映射中。看起来你应该这样做:

values.put( e_id, value );
subordinates.put( e_id, subordinate );

这应该可以解决问题!

关于java - 向 ArrayList 添加元素失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57932174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com