1145. Associated query
Given an employee table datalist1, store the employee ID and the employee name.
Given an employee hours table datalist2, store the employee ID, month, and hour.
Calculate the monthly working hours and total working hours of each employee from January to march.
Input description:
[[employee ID, employee name],[employee ID, employee name],...]
[[employee ID, month, hour, month, hour, month, hour],[employee ID, month, hour, month, hour, month, hour],...]
Output description:
[[employee name, January hours, February hours, march hours, total hours],[employee name, January hours, February hours, march hours, total hours],...]
Example
Input:
[["1","zhangwei01"]]
[["1","01","200","02","150","03","196"]]
Output:
[["zhangwei01","200","150","196","546"]]
Notice
The relevant data are presented in the two tables from small to large according to the employee ID, and the data in the returned table should also be arranged from small to large according to the employee ID.
解法1:
注意:atoi和stoi的区别。atoi是C语言用的,因为C语言不知道string,所以atoi的参数如果是string类型必须还要加个.c_str()将其转换成C语言的字符串。stoi可以直接用于C++的string。
class Solution {
public:
/**
* @param datalist1: a list represents the employee table
* @param datalist2: a list represents the employee hours table
* @return: Returns a list of strings represents the datalist3
*/
vector<vector<string>> getList(vector<vector<string>> &datalist1, vector<vector<string>> &datalist2) {
int num_employee = datalist1.size();
if (num_employee == 0) return {{}};
vector<vector<string>> result(num_employee, vector<string>(5));
for (int i = 0; i < num_employee; ++i) {
result[i][0] = datalist1[i][1];
int month_id = 0, sum_hours = 0;
month_id = stoi(datalist2[i][1]);
result[i][month_id] = datalist2[i][2];
sum_hours += stoi(datalist2[i][2]);
month_id = stoi(datalist2[i][3]);
result[i][month_id] = datalist2[i][4];
sum_hours += stoi(datalist2[i][4]);
month_id = stoi(datalist2[i][5]);
result[i][month_id] = datalist2[i][6];
sum_hours += stoi(datalist2[i][6]);
result[i][4] = to_string(sum_hours);
}
return result;
}
};