leetcode 475. Heaters | 475. 供暖器(找最后一个不大于target的值/第一个不小于target的值)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 475. Heaters | 475. 供暖器(找最后一个不大于target的值/第一个不小于target的值)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/heaters/
題解
class Solution {public int findRadius(int[] houses, int[] heaters) {Arrays.sort(heaters);int max = Integer.MIN_VALUE;for (int house : houses) {int floor = floor(heaters, house, 0, heaters.length - 1);int ceiling = ceiling(heaters, house, 0, heaters.length - 1);if (floor >= 0 && ceiling >= 0)max = Math.max(max, Math.min(Math.abs(floor - house), Math.abs(ceiling - house)));else if (floor >= 0) max = Math.max(max, Math.abs(floor - house));else max = Math.max(max, Math.abs(ceiling - house));}return max;}// 找最后一個不大于target的值public int ceiling(int[] arr, int target, int L, int R) {if (arr[0] > target) return -1;while (L < R) {int M = (L + R + 1) / 2; // 讓M靠R側if (arr[M] == target) {return arr[M];} else if (arr[M] < target) { // 保左端點if (L == M) return arr[L];L = M;} else {R = M - 1;}}if (L >= arr.length) return -1;else return arr[L];}// 找第一個不小于target的值public int floor(int[] arr, int target, int L, int R) {if (arr[R] < target) return -1;while (L < R) {int M = (L + R) / 2; // 讓M靠L側if (arr[M] == target) {return arr[M];} else if (arr[M] < target) {L = M + 1;} else { // 保右端點if (R == M) return arr[M];R = M;}}if (L >= arr.length) return -1;else return arr[L];} }總結
以上是生活随笔為你收集整理的leetcode 475. Heaters | 475. 供暖器(找最后一个不大于target的值/第一个不小于target的值)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 474. Ones a
- 下一篇: leetcode 95. Unique