Leetcode - Best Meeting Point

My code:

public class Solution {
    public int minTotalDistance(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return -1;
        }
        
        int row = grid.length;
        int col = grid[0].length;
        int[] row_compress = new int[col];
        int[] col_compress = new int[row];
        
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                row_compress[j] += grid[i][j];
                col_compress[i] += grid[i][j];
            }
        }
        
        return helper(row_compress) + helper(col_compress);
    }
    
    private int helper(int[] arr) {
        int i = -1;
        int j = arr.length;
        int left = 0;
        int right = 0;
        int d = 0;
        while (i != j) {
            if (left < right) {
                d += left;
                left += arr[++i];
            }
            else {
                d += right;
                right += arr[--j];
            }
        }
        return d;
    }
}

reference:
https://discuss.leetcode.com/topic/27762/java-2ms-python-40ms-two-pointers-solution-no-median-no-sort-with-explanation

https://leetcode.com/articles/best-meeting-point/#approach-3-sorting-accepted

这道题目真是卡了很久,到现在其实也没完全懂。暂且记下这个做法吧。

Anyway, Good luck, Richardo! -- 10/08/2016

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容