Leetcode Top100 Part. 1 20201104
Leetcode 461. 汉明距离
两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。 给出两个整数 x 和 y,计算它们之间的汉明距离。 注 0 ≤ x,
y < 231. 示例: 输入: x = 1, y = 4 输出: 2
解释:
1 (0 0 0 1)
4 (0 1 0 0)
分析:
1、对x和y进行异或,判断其中1的位数
2、判断最后一位是否为1,并每次将异或结果右移一位
class Solution {
public int hammingDistance(int x, int y) {
int xor = x ^ y;
int hanmingDis = 0;
while (xor != 0) {
if (xor % 2 == 1) {
hanmingDis++;
}
xor = xor >> 1;
}
return hanmingDis;
}
}
Leetcode 226.翻转二叉树
Leetcode 104.二叉树深度
Leetcode 136.只出现一次的数字
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
因此数组中全部数字的异或结果即为只出现一次的数字。
class Solution {
public int singleNumber(int[] nums) {
int temp = 0;
for (int num: nums) {
temp ^= num;
}
return temp;
}
}
Leetcode 169. 多数元素
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
思路:1、摩尔投票法
首先,初始化结果result=nums[0],count=1。然后遍历数组,当遇到相同的元素时count加一,当遇到不同的元素时count减一。当count等于0时,更换result为当前数值,并重置count为1。
class Solution {
public int majorityElement(int[] nums) {
int ans = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i ++) {
if (nums[i] != ans) {
count--;
} else {
count++;
}
if (count == 0) {
ans = nums[i];
count = 1;
}
}
return ans;
}
}