LeetCode 475 - Heaters


https://leetcode.com/problems/heaters/
Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.
Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.
So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.
Note:
  1. Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
  2. Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
  3. As long as a house is in the heaters' warm radius range, it can be warmed.
  4. All the heaters follow your radius standard and the warm radius will the same.
Example 1:
Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
Example 2:
Input: [1,2,3,4],[1,4]
Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
https://blog.csdn.net/elliott_yoho/article/details/78578277
题意大致为,在一条水平线上有若干房间和加热器,给定房间和加热器的坐标,求加热器所需的最小供暖范围,使得所有房间有加热器为其供暖。

http://www.cnblogs.com/grandyang/p/6181626.html
这道题是一道蛮有意思的题目,首先我们看题目中的例子,不管是houses还是heaters数组都是有序的,所以我们也需要给输入的这两个数组先排序,以免其为乱序。我们就拿第二个例子来分析,我们的目标是houses中的每一个数字都要被cover到,那么我们就遍历houses数组,对每一个数组的数字,我们在heaters中找能包含这个数字的左右范围,然后看离左右两边谁近取谁的值,如果某个house位置比heaters中最小的数字还小,那么肯定要用最小的heater去cover,反之如果比最大的数字还大,就用最大的数字去cover。对于每个数字算出的半径,我们要取其中最大的值。通过上面的分析,我们就不难写出代码了,我们在heater中两个数一组进行检查,如果后面一个数和当前house位置差的绝对值小于等于前面一个数和当前house位置差的绝对值,那么我们继续遍历下一个位置的数。跳出循环的条件是遍历到heater中最后一个数,或者上面的小于等于不成立,此时heater中的值和当前house位置的差的绝对值就是能cover当前house的最小半径,我们更新结果res即可

X. https://leetcode.com/problems/heaters/discuss/95886/Short-and-Clean-Java-Binary-Search-Solution
The idea is to leverage decent Arrays.binarySearch() function provided by Java.
  1. For each house, find its position between those heaters (thus we need the heaters array to be sorted).
  2. Calculate the distances between this house and left heater and right heater, get a MIN value of those two values. Corner cases are there is no left or right heater.
  3. Get MAX value among distances in step 2. It's the answer.
Time complexity: max(O(nlogn), O(mlogn)) - m is the length of houses, n is the length of heaters.
I am sharing my solution. The idea is to find the closest heater to each house and take maximum of the closest distances. Thus initially it is necessary to sort both houses and heaters by their coordinates. Then assign two pointers, one for houses and another for heaters. Then start traversing the houses. If the ith house is located between j-1th heater and jth heater, then take distance to the closest one and check whether it is the maximum radius found so far. The corner cases are when a house is located before the 1st heater, and when a house is located after the last heater. At the corner case position, there are only distance to consider. That's it. I think code will clarify the idea more.

    public int findRadius(int[] houses, int[] heaters) {
        if(houses == null || houses.length == 0) return 0;
        Arrays.sort(houses);
        Arrays.sort(heaters);
        int ans = 0;
        int i  = 0;
        int j = 0;
        while(i<houses.length){
            if(houses[i] <= heaters[j]){ //if house is located before heater j.
                if(j == 0){ // corner case when the heater is the first  one
                    ans = Math.max(ans, heaters[j]-houses[i]);
                    i++;
                    continue;
                }
            } else { // if house is located after some heater, 
                while(j!=heaters.length-1 && heaters[j]<houses[i]){ // then find a heater that stands after the house
                    j++;
                }
                if(j == 0 || heaters[j] < houses[i]){ // corner cases if j is 0 or there is no more heaters
                    ans = Math.max(ans, houses[i]-heaters[j]);
                    i++;
                    continue;
                }
            }
            int dist = Math.min(houses[i]-heaters[j-1], heaters[j]-houses[i]); // if house is located between jth and j-1th heaters
            ans = Math.max(ans, dist);
            i++;
        }
        
        return ans;
    }

X.

主要思路为对每一个房间,寻找离他最近的加热器,统计这些房间与离他最近的加热器的距离,在这些距离中取最大值即为所求。

具体实现的话,首先对加热器的位置进行排序,按照从小到大的顺序。然后对每一个房间,在加热器数组中用二分查找算法找到离他最近的加热器的位置,计算距离并更新目标半径。

另外,我用的二分查找为”在数组中找到最后一个小于等于目标值的下标,若不存在则返回-1“,因此除了二分查找得到的下标 index 对应的加热器与该房间距离,还要比较下标为 index + 1 的加热器与房间的距离,取两者之间较小值。
https://discuss.leetcode.com/topic/71460/short-and-clean-java-binary-search-solution
The idea is to leverage decent Arrays.binarySearch() function provided by Java.
  1. For each house, find its position between those heaters (thus we need the heaters array to be sorted).
  2. Calculate the distances between this house and left heater and right heater, get a MIN value of those two values. Corner cases are there is no left or right heater.
  3. Get MAX value among distances in step 2. It's the answer.
Time complexity: max(O(nlogn), O(mlogn)) - m is the length of houses, n is the length of heaters.
    public int findRadius(int[] houses, int[] heaters) {
        Arrays.sort(heaters);
        int result = Integer.MIN_VALUE;
        
        for (int house : houses) {
         int index = Arrays.binarySearch(heaters, house);
         if (index < 0) {
          index = -(index + 1);
         }
         int dist1 = index - 1 >= 0 ? house - heaters[index - 1] : Integer.MAX_VALUE;
         int dist2 = index < heaters.length ? heaters[index] - house : Integer.MAX_VALUE;
         
         result = Math.max(result, Math.min(dist1, dist2));
        }
        
        return result;
    }
Just a small variation (we can ignore houses on heaters, and I like ~):
public int findRadius(int[] houses, int[] heaters) {
    Arrays.sort(heaters);
    int result = 0;
    
    for (int house : houses) {
        int index = Arrays.binarySearch(heaters, house);
        if (index < 0) {
            index = ~index;
            int dist1 = index - 1 >= 0 ? house - heaters[index - 1] : Integer.MAX_VALUE;
            int dist2 = index < heaters.length ? heaters[index] - house : Integer.MAX_VALUE;
            
            result = Math.max(result, Math.min(dist1, dist2));
        }
    }
    
    return result;
}
http://bookshadow.com/weblog/2016/12/11/leetcode-heaters/
升序排列加热器的坐标heaters

遍历房屋houses,记当前房屋坐标为house:

    利用二分查找,分别找到不大于house的最大加热器坐标left,以及不小于house的最小加热器坐标right
    
    则当前房屋所需的最小加热器半径radius = min(house - left, right - house)
    
    利用radius更新最终答案ans
X. TreeSet
Initially I was trying TreeSet as it provides easier way to find the lowerBound and upperBound. While I mistakenly reversed the min and max relationship when updating the global min radius result. Thanks to @ckcz123 's solution and I realized my error and made it right.
The idea using TreeSet is first put heaters' location into the tree, then iterate the houses' location finding the smallest radius with which one of the closest heaters may cover. Say heaters[1, 4] , houses[1,2,3,4]. When we scan the house = 1, found closest heater is at 1, so the global max till house at 1 is 0; then when house = 2, found the closest heater is min(house at 2 - heater at 1, heater at 4 - house at 2) = 1, which means the heater at 1 can cover the house at 2 and we do not need to use heater at 4. In the end, we may found the global res (min radius required) and remember that some of the heaters may not be effectively used as long as all the houses are already covered. O(logn) for TreeSet operations in this solution, but need O(heater) space which is not as good as binary search solution.
public class Solution {
    public int findRadius(int[] houses, int[] heaters) {
        TreeSet<Integer> treeset = new TreeSet<>();
        for (int heater : heaters) treeset.add(heater);
        int res = 0;
        for (int house : houses) {
            Integer upper = treeset.ceiling(house); 
            Integer lower = treeset.floor(house);
            res = Math.max(res, Math.min(upper == null ? Integer.MAX_VALUE : upper - house, lower == null ? Integer.MAX_VALUE : house - lower));
        }
        return res;
    }
}

X.  Two Pointers
Based on 2 pointers, the idea is to find the nearest heater for each house, by comparing the next heater with the current heater.
    public int findRadius(int[] houses, int[] heaters) {
        Arrays.sort(houses);
        Arrays.sort(heaters);
        
        int i = 0, j = 0, res = 0;
        while (i < houses.length) {
            while (j < heaters.length - 1
                && Math.abs(heaters[j + 1] - houses[i]) <= Math.abs(heaters[j] - houses[i])) {
                j++;
            }
            res = Math.max(res, Math.abs(heaters[j] - houses[i]));
            i++;
        }
        
        return res;
    }
Updated solution inspired by @StefanPochmann
    public int findRadius(int[] houses, int[] heaters) {
        Arrays.sort(houses);
        Arrays.sort(heaters);
        
        int i = 0, res = 0;
        for (int house : houses) {
            while (i < heaters.length - 1 && heaters[i] + heaters[i + 1] <= house * 2) {
                i++;
            }
            res = Math.max(res, Math.abs(heaters[i] - house));
        }
        
        return res;
    }
Example:    h = house,  * = heater  M = INT_MAX

        h   h   h   h   h   h   h   h   h    houses
        1   2   3   4   5   6   7   8   9    index
        *           *       *                heaters
                
        0   2   1   0   1   0   -   -   -    (distance to nearest RHS heater)
        0   1   2   0   1   0   1   2   3    (distance to nearest LHS heater)

        0   1   1   0   1   0   1   2   3    (res = minimum of above two)

Result is maximum value in res, which is 3.
*/
    int findRadius(vector<int>& A, vector<int>& H) {
        sort(A.begin(), A.end());
        sort(H.begin(), H.end());
        vector<int> res(A.size(), INT_MAX); 
        
        // For each house, calculate distance to nearest RHS heater
        for (int i = 0, h = 0; i < A.size() && h < H.size(); ) {
            if (A[i] <= H[h]) { res[i] = H[h] - A[i]; i++; }
            else { h++; }
        }
        
        // For each house, calculate distance to nearest LHS heater
        for (int i = A.size()-1, h = H.size()-1; i >= 0 && h >= 0; ) {
            if (A[i] >= H[h]) { res[i] = min(res[i], A[i] - H[h]); i--; }
            else { h--; }
        }
       
        return *max_element(res.begin(), res.end());
    }
}



Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts