heaters

https://leetcode.com/problems/heaters/

 

开始的时候,下面的代码对于两边数字完全一样的情况,测试不通过。原因是heater会有重复情况,这时候对于飘红部分就不会往前面继续检查。所以把<改成<=让相同的情况也继续往前面走,走到最后一个,就可以了。Accepted!

package com.company;

import java.util.Arrays;

class Solution {
    public int findRadius(int[] houses, int[] heaters) {
        Arrays.sort(houses);
        Arrays.sort(heaters);

        int ret = Integer.MIN_VALUE;
        int i = 0;
        int hlen = heaters.length;
        int tmp = Integer.MIN_VALUE;
        for (int h: houses) {
            while (i+1 < hlen && Math.abs(heaters[i+1]-h) <= Math.abs(heaters[i]-h)) {
                i++;
            }
            if (Math.abs(heaters[i]-h) > ret) {
                ret = Math.abs(heaters[i]-h);
            }
        }
        return ret;
    }
}

public class Main {


    public static void main(String[] args) {

        Solution solution = new Solution();

        int[] houses = {1, 2, 2, 3, 4, 5};
        int[] heaters = {1, 2, 2, 3, 4, 5};
        int ret = solution.findRadius(houses, heaters);

        System.out.printf("Done ret: %d\n", ret);

    }

}

 

posted @ 2016-12-15 15:48  blcblc  阅读(303)  评论(0编辑  收藏  举报