Advertisement
uopspop

Untitled

Jul 8th, 2021
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. class Solution {
  2. public int findRadius(int[] houses, int[] heaters) {
  3. int len_min = Integer.MIN_VALUE;
  4.  
  5. Arrays.sort(heaters);
  6.  
  7. for (int i = 0; i < houses.length ;i++) {
  8. int pos_house = houses[i];
  9. find_closest_left_right_pos(pos_house, heaters, 0, heaters.length - 1);
  10.  
  11. Integer radius_shorter = null;
  12. if (pos_heater_left != null && pos_heater_right != null) {
  13. int radius_heater_left = Math.abs(pos_house - pos_heater_left);
  14. int radius_heater_right = Math.abs(pos_heater_right - pos_house);
  15. radius_shorter = Math.min(radius_heater_left, radius_heater_right); // pick nearer one
  16. }else if (pos_heater_left != null) {
  17. radius_shorter = Math.abs(pos_house - pos_heater_left);
  18. }else if (pos_heater_right != null) {
  19. radius_shorter = Math.abs(pos_heater_right - pos_house);
  20. }
  21.  
  22. if (radius_shorter != null) {
  23. len_min = Math.max(len_min, radius_shorter); // attention: this is max - the lowest requirement
  24. }
  25.  
  26. }
  27.  
  28.  
  29. return len_min;
  30. }
  31.  
  32. Integer pos_heater_left = null;
  33. Integer pos_heater_right = null;
  34. public void find_closest_left_right_pos(int pos_house, int[] heaters, int i_left, int i_right) {
  35. if (i_left > i_right) return;
  36.  
  37. int i_mid = (i_left + i_right) / 2;
  38. int pos_heater = heaters[i_mid];
  39. if (pos_house == pos_heater) {
  40. pos_heater_left = pos_heater;
  41. pos_heater_right = pos_heater;
  42. }else if (pos_house > pos_heater) {
  43. pos_heater_left = pos_heater;
  44. find_closest_left_right_pos(pos_house, heaters, i_mid + 1, i_right);
  45. }else if (pos_house < pos_heater) {
  46. pos_heater_right = pos_heater;
  47. find_closest_left_right_pos(pos_house, heaters, i_left, i_mid - 1);
  48. }
  49.  
  50. return;
  51. }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement