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

這道題目真是卡了很久,到現(xiàn)在其實也沒完全懂。暫且記下這個做法吧。

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容