Skip to content

Commit 0298b44

Browse files
authored
Update Find the Prefix Common Array of Two Arrays.java
1 parent 9d40369 commit 0298b44

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

Medium/Find the Prefix Common Array of Two Arrays.java

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
class Solution {
22
public int[] findThePrefixCommonArray(int[] A, int[] B) {
3-
Map<Integer, Integer> map = new HashMap<>();
43
int count = 0;
5-
int[] result = new int[A.length];
6-
for (int i = 0; i < A.length; i++) {
7-
map.put(A[i], map.getOrDefault(A[i], 0) + 1);
8-
map.put(B[i], map.getOrDefault(B[i], 0) + 1);
9-
count += map.get(A[i]) == 2 ? 1 : 0;
10-
if (A[i] != B[i]) {
11-
count += map.get(B[i]) == 2 ? 1 : 0;
4+
int n = A.length;
5+
int[] result = new int[n];
6+
int[] frequency = new int[n + 1];
7+
for (int i = 0; i < n; i++) {
8+
frequency[A[i]]++;
9+
if (frequency[A[i]] == 2) {
10+
count++;
11+
}
12+
frequency[B[i]]++;
13+
if (frequency[B[i]] == 2) {
14+
count++;
1215
}
1316
result[i] = count;
1417
}

0 commit comments

Comments
 (0)