This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
/** | |
* @param operations: the type of information | |
* @param name: the name of user | |
* @param w: the money need to save or take | |
* @return: output the remaining money of the user.if the operation is illegal,output -1 | |
*/ | |
public int[] getAns(int[] operations, String[] names, int[] amounts) { | |
// Write your code here | |
if (operations == null || operations.length == 0) { | |
return new int[0]; | |
} | |
int n = operations.length; | |
int[] result = new int[n]; | |
Map<String, Integer> name2Balance = new HashMap<>(); | |
for (int i = 0; i < n; i++) { | |
int op = operations[i]; | |
String name = names[i]; | |
int amount = amounts[i]; | |
if (op == 0) { | |
int balance = name2Balance.getOrDefault(name, 0) + amount; | |
name2Balance.put(name, balance); | |
result[i] = balance; | |
} else { | |
if (name2Balance.getOrDefault(name, 0) >= amount) { | |
int balance = name2Balance.getOrDefault(name, 0) - amount; | |
name2Balance.put(name, balance); | |
result[i] = balance; | |
} else { | |
result[i] = -1; | |
} | |
} | |
} | |
return result; | |
} | |
} |
No comments:
Post a Comment