I've tested my code with MAX/MIN, positives/negatives, different ordering of numbers, huge array, characters, null array, still failed 2 hidden test cases. Legit scratching my head finding all the possible test cases. Any tips to find out about passing hidden test cases?
Task: Write a function called solution(data, n) that takes in a list of less than 100 integers and a number n, and returns that same list but with all of the numbers that occur more than n times removed entirely. The returned list should retain the same ordering as the original list - you don't want to mix up those carefully-planned shift rotations! For instance, if data was [5, 10, 15, 10, 7] and n was 1, solution(data, n) would return the list [5, 15, 7] because 10 occurs twice, and thus was removed from the list entirely.
Input: Solution.solution({1, 2, 3}, 0) Output:
Input: Solution.solution({1, 2, 2, 3, 3, 3, 4, 5, 5}, 1) Output: 1,4
class Solution {
public static int[] solution(int[] data, int n) {
if (data == null) return new int[]{};
Map<Integer, Integer> dataWithCount = new LinkedHashMap<Integer, Integer>();
for (int i = 0; i < data.length; i++) {
if (dataWithCount.containsKey(data[i])) {
dataWithCount.put(data[i], dataWithCount.get(data[i]) + 1);
} else {
dataWithCount.put(data[i], 1);
}
}
Iterator<Map.Entry<Integer, Integer>> iter = dataWithCount.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<Integer, Integer> entry = iter.next();
if (entry.getValue() > n) {
iter.remove();
}
}
int[] newArray = new int[dataWithCount.size()];
int newArrIndex = 0;
for (Map.Entry<Integer, Integer> entry: dataWithCount.entrySet()) {
newArray[newArrIndex++] = entry.getKey();
}
return newArray;
}
}
Aucun commentaire:
Enregistrer un commentaire