Apply suggestions from code review
Co-authored-by: Du Yuanchao <shellhub.me@gmail.com>
This commit is contained in:
parent
cccc898ba1
commit
bbe6f9410c
@ -18,6 +18,7 @@ public class Mode {
|
|||||||
/* Test array of integers */
|
/* Test array of integers */
|
||||||
assert (mode(new int[]{})) == null;
|
assert (mode(new int[]{})) == null;
|
||||||
assert Arrays.equals(mode(new int[]{5}), new int[]{5});
|
assert Arrays.equals(mode(new int[]{5}), new int[]{5});
|
||||||
|
assert Arrays.equals(mode(new int[]{1, 2, 3, 4, 5}), new int[]{1, 2, 3, 4, 5});
|
||||||
assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 8}), new int[]{7});
|
assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 8}), new int[]{7});
|
||||||
assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 9}), new int[]{7, 9});
|
assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 9}), new int[]{7, 9});
|
||||||
|
|
||||||
@ -26,17 +27,16 @@ public class Mode {
|
|||||||
/*
|
/*
|
||||||
* Find the mode of an array of integers
|
* Find the mode of an array of integers
|
||||||
*
|
*
|
||||||
* @param int[] array of integers
|
* @param numbers array of integers
|
||||||
* @return int[] mode of the array
|
* @return mode of the array
|
||||||
*/
|
*/
|
||||||
public static int[] mode(int[] numbers) {
|
public static int[] mode(int[] numbers) {
|
||||||
|
|
||||||
if(numbers.length == 0) return null;
|
if(numbers.length == 0) return null;
|
||||||
|
|
||||||
HashMap<Integer, Integer> count = new HashMap<Integer, Integer>();
|
HashMap<Integer, Integer> count = new HashMap<>();
|
||||||
|
|
||||||
for(int num : numbers) {
|
for(int num : numbers) {
|
||||||
|
|
||||||
if(count.containsKey(num)) {
|
if(count.containsKey(num)) {
|
||||||
|
|
||||||
count.put(num, count.get(num) + 1);
|
count.put(num, count.get(num) + 1);
|
||||||
@ -50,20 +50,14 @@ public class Mode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int max = Collections.max(count.values());
|
int max = Collections.max(count.values());
|
||||||
ArrayList<Integer> modes = new ArrayList<Integer>();
|
ArrayList<Integer> modes = new ArrayList<>();
|
||||||
|
|
||||||
for(int num : count.keySet()) {
|
for(int num : count.keySet()) {
|
||||||
|
|
||||||
if(count.get(num) == max) {
|
if(count.get(num) == max) {
|
||||||
|
|
||||||
modes.add(num);
|
modes.add(num);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return modes.stream().mapToInt(n -> n).toArray();
|
return modes.stream().mapToInt(n -> n).toArray();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user