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: lcci/16.01.Swap Numbers/README_EN.md
+20Lines changed: 20 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -24,6 +24,26 @@
24
24
25
25
## Solutions
26
26
27
+
**Solution 1: Bitwise Operation**
28
+
29
+
We can use the XOR operation $\oplus$ to implement the swap of two numbers.
30
+
31
+
The XOR operation has the following three properties:
32
+
33
+
- Any number XORed with $0$ remains unchanged, i.e., $a \oplus 0=a$.
34
+
- Any number XORed with itself results in $0$, i.e., $a \oplus a=0$.
35
+
- The XOR operation satisfies the commutative and associative laws, i.e., $a \oplus b \oplus a=b \oplus a \oplus a=b \oplus (a \oplus a)=b \oplus 0=b$.
36
+
37
+
Therefore, we can perform the following operations on two numbers $a$ and $b$ in the array $numbers$:
38
+
39
+
- $a=a \oplus b$, now $a$ stores the XOR result of the two numbers;
40
+
- $b=a \oplus b$, now $b$ stores the original value of $a$;
41
+
- $a=a \oplus b$, now $a$ stores the original value of $b$;
42
+
43
+
In this way, we can swap two numbers without using a temporary variable.
44
+
45
+
The time complexity is $O(1)$, and the space complexity is $O(1)$.
We use a hash table $cnt$ to count the number of occurrences of each word in $book$.
48
+
49
+
When calling the `get` function, we only need to return the number of occurrences of the corresponding word in $cnt$.
50
+
51
+
In terms of time complexity, the time complexity of initializing the hash table $cnt$ is $O(n)$, where $n$ is the length of $book$. The time complexity of the `get` function is $O(1)$. The space complexity is $O(n)$.
0 commit comments