Skip to content

Commit a61b451

Browse files
authored
Refactored Set Mismatch.java to functional style
1 parent d4bc7da commit a61b451

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

Easy/Set Mismatch.java

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,14 @@
1+
import java.util.Map.Entry;
2+
13
class Solution {
24
public int[] findErrorNums(int[] nums) {
3-
Map<Integer, Integer> frequency = new HashMap<>();
4-
for (int num : nums) {
5-
frequency.put(num, frequency.getOrDefault(num, 0) + 1);
6-
}
7-
int[] ans = new int[2];
8-
for (int idx = 1; idx <= nums.length; idx++) {
9-
if (!frequency.containsKey(idx)) {
10-
ans[1] = idx;
11-
} else if (frequency.get(idx) > 1) {
12-
ans[0] = idx;
13-
}
14-
}
15-
return ans;
5+
HashMap<Integer, Long> frequencyMap = Arrays.stream(nums).boxed()
6+
.collect(Collectors.groupingBy(Function.identity(), HashMap::new, Collectors.counting()));
7+
return new int[]{
8+
frequencyMap.entrySet().stream().filter(entry -> entry.getValue().equals(2L))
9+
.map(Entry::getKey).findFirst().orElse(-1),
10+
IntStream.range(1, nums.length + 1).boxed().filter(key -> !frequencyMap.containsKey(key))
11+
.findFirst().orElse(-1)
12+
};
1613
}
1714
}

0 commit comments

Comments
 (0)