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

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/bcccc09ec12d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞