You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/README_EN.md
+112-8
Original file line number
Diff line number
Diff line change
@@ -45,15 +45,27 @@ At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3.
45
45
46
46
## Solutions
47
47
48
-
**Solution 1: Count + Enumeration**
48
+
**Solution 1: Counting**
49
49
50
-
We can use two arrays $cnt1$ and $cnt2$ to record the number of occurrences of each element in arrays $A$ and $B$, and use array $ans$ to record the answer.
50
+
We can use two arrays $cnt1$ and $cnt2$ to record the occurrence times of each element in arrays $A$ and $B$ respectively, and use an array $ans$ to record the answer.
51
51
52
-
Traverse arrays $A$ and $B$, add the number of occurrences of $A[i]$ in $cnt1$ by one, and add the number of occurrences of $B[i]$ in $cnt2$ by one. Then enumerate $j \in [1,n]$, calculate the minimum value of the number of occurrences of each element $j$ in $cnt1$ and $cnt2$, and add it to $ans[i]$.
52
+
Traverse arrays $A$ and $B$, increment the occurrence times of $A[i]$ in $cnt1$, and increment the occurrence times of $B[i]$ in $cnt2$. Then enumerate $j \in [1,n]$, calculate the minimum occurrence times of each element $j$ in $cnt1$ and $cnt2$, and accumulate them into $ans[i]$.
53
53
54
-
After the traversal is over, return the answer array $ans$.
54
+
After the traversal, return the answer array $ans$.
55
55
56
-
The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the length of arrays $A$ and $B$.
56
+
The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of arrays $A$ and $B$.
57
+
58
+
**Solution 2: Bit Operation (XOR Operation)**
59
+
60
+
We can use an array $vis$ of length $n+1$ to record the occurrence situation of each element in arrays $A$ and $B$, the initial value of array $vis$ is $1$. In addition, we use a variable $s$ to record the current number of common elements.
61
+
62
+
Next, we traverse arrays $A$ and $B$, update $vis[A[i]] = vis[A[i]] \oplus 1$, and update $vis[B[i]] = vis[B[i]] \oplus 1$, where $\oplus$ represents XOR operation.
63
+
64
+
If at the current position, the element $A[i]$ has appeared twice (i.e., it has appeared in both arrays $A$ and $B$), then the value of $vis[A[i]]$ will be $1$, and we increment $s$. Similarly, if the element $B[i]$ has appeared twice, then the value of $vis[B[i]]$ will be $1$, and we increment $s$. Then add the value of $s$ to the answer array $ans$.
65
+
66
+
After the traversal, return the answer array $ans$.
67
+
68
+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of arrays $A$ and $B$.
0 commit comments