Leetcode每日随机2021/4/19

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

面试题17.14

leetcode1091
就是一道普普通通的bfs,额外记录一下当前步数即可

代码

面试题17.14

class Solution {
    public int[] smallestK(int[] arr, int k) {
		Queue<Integer> queue = new PriorityQueue<Integer>((a, b) -> b - a);
		for (Integer i : arr) {
			queue.offer(i);
			if (queue.size() > k) {
				queue.poll();
			}
		}
		int[] res = new int[k];
		int idx = 0;
		while (!queue.isEmpty()) {
			res[idx++] = queue.poll();
		}
		return res;
	}
}

leetcode1091

class Solution {
    Map<String, Integer> visited = new HashMap<String, Integer>();
	Queue<String> queue = new LinkedList<String>();

	public int shortestPathBinaryMatrix(int[][] grid) {
		if (grid[0][0] == 1 || grid[grid.length - 1][grid.length - 1] == 1) {
			return -1;
		}
		int minStep = -1;
		visited.put("0,0", 1);
		queue.offer("0,0");
		while (!queue.isEmpty()) {
			String[] posStr = queue.poll().split(",");
			int row = Integer.valueOf(posStr[0]);
			int col = Integer.valueOf(posStr[1]);
			if (row == grid.length - 1 && col == grid.length - 1) {
				minStep = visited.get(row + "," + col);
				break;
			}
			bfs(row, col, grid);
		}
		return minStep;
	}

	private void bfs(int row, int col, int[][] grid) {
		int step = visited.get(row + "," + col) + 1;
		int[][] possiblePos = { { row - 1, col - 1 }, { row - 1, col }, { row - 1, col + 1 }, { row, col - 1 },
				{ row, col + 1 }, { row + 1, col - 1 }, { row + 1, col }, { row + 1, col + 1 } };
		for (int[] pos : possiblePos) {
			if (pos[0] >= 0 && pos[0] < grid.length && pos[1] >= 0 && pos[1] < grid.length && grid[pos[0]][pos[1]] == 0
					&& !visited.containsKey(pos[0] + "," + pos[1])) {
				queue.offer(pos[0] + "," + pos[1]);
				visited.put(pos[0] + "," + pos[1], step);
			}
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值