题
思
leetcode1631
bfs暴力解的,记录到达当前节点的最小的体力值消耗,直至所有节点不在有更新(队列为空)。
leetcode1356
弱智题。
代码
leetcode1631
class Solution {
public int minimumEffortPath(int[][] heights) {
Map<String, Integer> map = new HashMap<String, Integer>();
Queue<String> queue = new LinkedList<String>();
queue.offer("0,0");
map.put("0,0", 0);
while (!queue.isEmpty()) {
String temp = queue.poll();
String[] idxs = temp.split(",");
int row = Integer.valueOf(idxs[0]);
int col = Integer.valueOf(idxs[1]);
if (row > 0) {
String top = row - 1 + "," + col;
Integer len = Math.max(Math.abs(heights[row][col] - heights[row - 1][col]), map.get(temp));
if (map.getOrDefault(top, Integer.MAX_VALUE) > len) {
map.put(top, len);
queue.offer(top);
}
}
if (col > 0) {
String left = row + "," + (col - 1);
Integer len = Math.max(Math.abs(heights[row][col] - heights[row][col - 1]), map.get(temp));
if (map.getOrDefault(left, Integer.MAX_VALUE) > len) {
map.put(left, len);
queue.offer(left);
}
}
if (row < heights.length - 1) {
String bottom = row + 1 + "," + col;
Integer len = Math.max(Math.abs(heights[row][col] - heights[row + 1][col]), map.get(temp));
if (map.getOrDefault(bottom, Integer.MAX_VALUE) > len) {
map.put(bottom, len);
queue.offer(bottom);
}
}
if (col < heights[0].length - 1) {
String right = row + "," + (col + 1);
Integer len = Math.max(Math.abs(heights[row][col] - heights[row][col + 1]), map.get(temp));
if (map.getOrDefault(right, Integer.MAX_VALUE) > len) {
map.put(right, len);
queue.offer(right);
}
}
}
return map.get(heights.length - 1 + "," + (heights[0].length - 1));
}
}
leetcode1356
class Solution {
public int[] sortByBits(int[] arr) {
Map<Integer, Integer> oneCount = new HashMap<Integer, Integer>();
Integer[] arr_copy = IntStream.of(arr).boxed().toArray(Integer[]::new);
for (int i = 0; i < arr.length; i++) {
String binary = Integer.toBinaryString(arr[i]);
oneCount.put(arr[i], binary.length() - binary.replaceAll("1", "").length());
}
Arrays.sort(arr_copy, (a, b) -> oneCount.get(a) == oneCount.get(b) ? a - b : oneCount.get(a) - oneCount.get(b));
return Arrays.stream(arr_copy).mapToInt(Integer::valueOf).toArray();
}
}