1. Hamming distance (461)
Title description:
【simple】
The Hamming distance between two integers refers to the number of positions where the two numbers correspond to different binary digits.
Given two integers x and y, calculate the Hamming distance between them.
Note:
0 ≤ x, y <2 31. 0 ≤ x, y <2^{31}.0≤x,Y<2. 3 . 1 .
Example:
输入: x = 1, y = 4
输出: 2
解释:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
Thinking analysis:
1. First is binary
2. Think of binary bitwise XOR operation: when two corresponding bits are different, the result is 1, and when they are the same, it is 0.
3. Then we can perform XOR operation on the two numbers, and then count Number of 1
answer:
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return bin(x^y).count("1")#进行异或操作然后转换成二进制
-
Time complexity: O (1) O (1)O ( 1 )
-
Space complexity: O (1) O (1)O ( 1 )
2. Numbers that appear only once (136)
Title description:
[Simple]
Given an array of non-empty integers, except for an element that appears only once, every other element appears twice. Find the element that appears only once.
Description:
Your algorithm should have linear time complexity. Can you do it without using extra space?
Example 1:
输入: [2,2,1]
输出: 1
Thinking analysis:
1. Because the problem requires the use of a constant space complexity
2. Therefore, we can use the exclusive OR operation of the bit operation to solve it
3. For this problem, the exclusive OR operation can be used. The XOR operation has the following three properties:
- Any number and 0 are XORed, the result is still the original number,
- XOR any number with itself, the result is 0
- The exclusive OR operation satisfies the commutative law and associative law
4. The result of the XOR of two identical numbers is 0. Perform an XOR operation on all numbers, and the final result is the number that appears alone.
answer:
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return reduce(lambda x, y: x ^ y, nums)
-
Time complexity: O (1) O (1)O ( 1 )
-
Space complexity: O (1) O (1)O ( 1 )