leecode更新

This commit is contained in:
markilue 2023-04-08 13:34:50 +08:00
parent 776e572905
commit 702985ce48
3 changed files with 279 additions and 0 deletions

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,69 @@
package com.markilue.leecode.hot100;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
*@BelongsProject: Leecode
*@BelongsPackage: com.markilue.leecode.hot100
*@Author: markilue
*@CreateTime: 2023-04-08 11:54
*@Description:
* TODO 力扣448 找到所有数组中的消失的数字:
* 给你一个含 n 个整数的数组 nums 其中 nums[i] 在区间 [1, n] 请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字并以数组的形式返回结果
*@Version: 1.0
*/
public class T92_FindDisappearedNumbers {
@Test
public void test(){
int[] nums = {4, 3, 2, 7, 8, 2, 3, 1};
System.out.println(findDisappearedNumbers(nums));
}
/**
* 思路:记录各个数字出现的次数为0则没有出现
* 速度击败99.36% 内存击败52.21% 3ms
* @param nums
* @return
*/
public List<Integer> findDisappearedNumbers(int[] nums) {
int[] counts = new int[nums.length + 1];
for (int num : nums) {
counts[num]++;
}
List<Integer> result = new ArrayList<>();
for (int i = 1; i < counts.length; i++) {
if (counts[i] == 0) result.add(i);
}
return result;
}
/**
* 官方题解:原地+n不影响实际结果
* 速度击败99.36% 内存击败26.85% 3ms
* @param nums
* @return
*/
public List<Integer> findDisappearedNumbers1(int[] nums) {
int n = nums.length;
for (int num : nums) {
int x = (num - 1) % n;
nums[x] += n;
}
List<Integer> ret = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if (nums[i] <= n) {
ret.add(i + 1);
}
}
return ret;
}
}

View File

@ -0,0 +1,40 @@
package com.markilue.leecode.hot100;
import org.junit.Test;
/**
*@BelongsProject: Leecode
*@BelongsPackage: com.markilue.leecode.hot100
*@Author: markilue
*@CreateTime: 2023-04-08 13:21
*@Description:
* TODO 力扣461 汉明距离:
* 两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目
* 给你两个整数 x y计算并返回它们之间的汉明距离
*@Version: 1.0
*/
public class T93_HammingDistance {
@Test
public void test() {
// System.out.println(3^1);
System.out.println(hammingDistance(1, 3));
}
/**
* 思路:异或之后得到不同位为1的值
* 然后num&(num-1)可以消除最后一个为1的值因此可以统计有几个1
* @param x
* @param y
* @return
*/
public int hammingDistance(int x, int y) {
int result = x ^ y;
int count = 0;
while (result != 0) {
count++;
result &= (result - 1);
}
return count;
}
}