Skip to content

Commit fb2a292

Browse files
committed
Refactored Set Mismatch.java
1 parent 8f621af commit fb2a292

File tree

1 file changed

+14
-23
lines changed

1 file changed

+14
-23
lines changed

Easy/Set Mismatch.java

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,17 @@
11
class Solution {
2-
public int[] findErrorNums(int[] nums) {
3-
int[] ans = {-1,1};
4-
Map<Integer, Integer> map = new HashMap<>();
5-
6-
for(int i=0;i<nums.length;i++) {
7-
if (map.containsKey(nums[i])) {
8-
map.put(nums[i], map.get(nums[i])+1);
9-
}
10-
else {
11-
map.put(nums[i], 1);
12-
}
13-
}
14-
15-
for (int i=1;i<=nums.length;i++) {
16-
if (!map.containsKey(i)) {
17-
ans[1] = i;
18-
}
19-
if (map.containsKey(i) && map.get(i) == 2) {
20-
ans[0] = i;
21-
}
22-
}
23-
24-
return ans;
2+
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);
256
}
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;
16+
}
2617
}

0 commit comments

Comments
 (0)