Leetcode刷题 2021.03.09
Leetcode440 字典序的第K小数字
给定整数 n 和 k,找到 1 到 n 中字典序第 k 小的数字。
唉,开始春招面试了以后真的没什么时间刷算法题了。只能先记录一下了,等后面有空的时候再回来看看吧。(字节常考题,多回来看看)
class Solution {
public int findKthNumber(int n, int k) {
int cur = 1;
int prefix = 1;
while (cur < k){
int count = helper(n, prefix);
if (cur + count > k){
prefix *= 10;
cur++;
}else{
prefix++;
cur += count;
}
}
return prefix;
}
private int helper(int n, int prefix){
long cur = prefix;
long next = cur + 1;
int count = 0;
while (cur <= n){
count += Math.min(n + 1, next) - cur;
cur *= 10;
next *= 10;
}
return count;
}
}
Leetcode224 基本计算器
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
class Solution {
public int calculate(String s) {
char[] arr = s.toCharArray();
Deque<Integer> stack = new ArrayDeque<>();
int i = 0, n = arr.length, sign = 1, res = 0;
stack.push(1);
while (i < n){
if (arr[i] == ' '){
i++;
}else if (arr[i] == '+'){
sign = stack.peek();
i++;
}else if (arr[i] == '-'){
sign = -stack.peek();
i++;
}else if (arr[i] == '('){
stack.push(sign);
i++;
}else if (arr[i] == ')'){
stack.pop();
i++;
}else {
long num = 0;
while (i < n && arr[i] >= '0' && arr[i] <= '9'){
num = num * 10 + arr[i] - '0';
i++;
}
res += sign * num;
}
}
return res;
}
}
Leetcode787 K 站中转内最便宜的航班
有 n 个城市通过 m 个航班连接。每个航班都从城市 u 开始,以价格 w 抵达 v。
现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到从 src 到 dst 最多经过 k 站中转的最便宜的价格。 如果没有这样的路线,则输出 -1。
这题用最朴素的迪杰斯特拉,效率差的一。
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
List<List<int[]>> edges = new ArrayList<>();
for(int i = 0; i < n; i++){
edges.add(new ArrayList<>());
}
for(int[] ele : flights){
edges.get(ele[0]).add(new int[]{ele[1], ele[2]});
}
PriorityQueue<Node> queue = new PriorityQueue<>((x, y) -> (x.dist - y.dist));
queue.offer(new Node(src, 0, K));
while (!queue.isEmpty()){
Node temp = queue.poll();
if (temp.index == dst) return temp.dist;
if (temp.k < 0) continue;
for(int[] ele : edges.get(temp.index)){
int next = ele[0];
queue.offer(new Node(next, temp.dist + ele[1], temp.k - 1));
}
}
return -1;
}
class Node{
int index;
int dist;
int k;
public Node(int index, int dist, int k){
this.index = index;
this.dist = dist;
this.k = k;
}
}
}