今天周赛就A了前面两个简单题,卡在第三题了,真是想复杂了;今日一题没想到用堆做。。。。菜呀
第三题 5728. 最少侧跳次数
代码:dp[i][j]表示到达第i处第j跑道的最少跳跃次数
class Solution {
public int minSideJumps(int[] obstacles) {
int len = obstacles.length;
int[][] dp = new int[len][3];
for(int i = 0;i<len;i++){
dp[i][0] = Integer.MAX_VALUE - 2;
dp[i][1] = Integer.MAX_VALUE - 2;
dp[i][2] = Integer.MAX_VALUE - 2;
}
dp[0][1] = 0;
dp[0][0] = 1;
dp[0][2] = 1;
for(int i = 1; i < len; i++){
if(obstacles[i] !=1) dp[i][0] = dp[i-1][0];
if(obstacles[i] !=2) dp[i][1] = dp[i-1][1];
if(obstacles[i] !=3) dp[i][2] = dp[i-1][2];
if(obstacles[i] !=1) dp[i][0] = Math.min(dp[i][0], Math.min(dp[i][1],dp[i][2]) + 1);
if(obstacles[i] !=2) dp[i][1] = Math.min(dp[i][1], Math.min(dp[i][0],dp[i][2]) + 1);
if(obstacles[i] !=3) dp[i][2] = Math.min(dp[i][2], Math.min(dp[i][0],dp[i][1]) + 1);
}
return Math.min(dp[len-1][0], Math.min(dp[len-1][1],dp[len-1][2]));
}
}
今日打卡题目:264. 丑数 II
代码:用最小堆来对丑数进行排序,并用Set来记录插入的元素是否重复
class Solution {
public int nthUglyNumber(int n) {
int[] factors = {2,3,5};
Set<Long> seen = new HashSet<Long>();
PriorityQueue<Long> heap = new PriorityQueue<Long>();
seen.add(1L);
heap.offer(1L);
int ugly = 0;
for(int i = 0; i < n; i++){
long curr = heap.poll();
ugly = (int)curr;
for(int factor: factors){
long next = curr*factor;
if(seen.add(next)){
heap.offer(next);
}
}
}
return ugly;
}
}