第一题
leetcode279. 完全平方数
public class 第一题10 {
public static int numSquares(int n) {
int[] dp = new int[n + 1];
for (int i = 1;i <= n;i++){
dp[i] = i;
for (int j = 1;j * j <= i;j++){
dp[i] = Math.min(dp[i - j * j],dp[i]);
}
}
return dp[n];
}
}
第二题
leetcode289. 生命游戏
思路:位运算
public class 第二题10 {
public static void gameOfLife(int[][] board) {
int n = board.length;
int m = board[0].length;
for (int i = 0;i < n;i++){
for (int j = 0;j < m;j++){
int neb = neighbors(i,j,board);
if (neb == 3 || (board[i][j] == 1 && neb == 3)){
board[i][j] |= 2;
}
}
}
for (int i = 0;i < n;i++){
for (int j = 0;j < m;j++){
board[i][j] >>>= 1;
}
}
}
private static int neighbors(int i, int j, int[][] board) {
return isAlive(i + 1,j,board) +
isAlive(i - 1,j,board) +
isAlive(i + 1,j + 1,board) +
isAlive(i - 1,j - 1,board) +
isAlive(i,j + 1,board) +
isAlive(i,j - 1,board) +
isAlive(i + 1,j - 1,board) +
isAlive(i - 1,j + 1,board);
}
private static int isAlive(int i, int j, int[][] board) {
return (i >= 0 && i < board.length && j >= 0 && j < board[0].length && (board[i][j] & 1) == 1) ? 1 : 0;
}
}
第三题
leetcode326. 3 的幂
public class 第三题10 {
public static boolean isPowerOfThree(int n) {
return n > 0 && 1162261467 % n == 0;
}
}
第四题
LeetCode340:至多包含 K 个不同字符的最长子串
思路:滑动窗口 + map
public class 第四题10 {
public static void main(String[] args) {
String res = maxStringWithK("aabcdbeeefg", 4);
System.out.println(res);
}
public static String maxStringWithK(String str,int k){
HashMap<Character, Integer> map = new HashMap<>();
int l = 0;
int r = 0;
int max = 0;
int index = 0;
while (r < str.length()){
map.put(str.charAt(r),map.getOrDefault(str.charAt(r),0) + 1);
while (map.size() > k && l < r){
map.put(str.charAt(l),map.get(str.charAt(l)) - 1);
if (map.get(str.charAt(l)) == 0){
map.remove(str.charAt(l));
}
l++;
}
if (max < (r - l + 1)){
max = r - l + 1;
index = l;
}
r++;
}
return str.substring(index,index + max);
}
}
第五题
leetcode380. O(1) 时间插入、删除和获取随机元素
public class 第五题10 {
public static void main(String[] args) {
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomizedSet.remove(2); // 返回 false ,表示集合中不存在 2 。
randomizedSet.insert(2); // 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomizedSet.getRandom(); // getRandom 应随机返回 1 或 2 。
randomizedSet.remove(1); // 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomizedSet.insert(2); // 2 已在集合中,所以返回 false 。
randomizedSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
}
static class RandomizedSet {
static int[] nums = new int[200010];
Random random = new Random();
Map<Integer, Integer> map = new HashMap<>();
int idx = -1;
public boolean insert(int val) {
if (map.containsKey(val)) return false;
nums[++idx] = val;
map.put(val, idx);
return true;
}
public boolean remove(int val) {
if (!map.containsKey(val)) return false;
int loc = map.remove(val);
if (loc != idx) map.put(nums[idx], loc);
nums[loc] = nums[idx--];
return true;
}
public int getRandom() {
return nums[random.nextInt(idx + 1)];
}
}
}