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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,663评论 2 45
  • 人的一生就是一本故事书,每天都在书写着属于今天的故事!其实我们每天都在讲述故事,只是在明天你才深有体会!有一本(在...
    鍩睿阅读 1,358评论 0 0
  • 犯罪案件系列的小说一般要么表现案件的离奇,要么表现破案者的洞察力,《烈日灼心》独树一帜,对两类潜逃者的分析刻画,让...
    l秦若水阅读 4,097评论 0 1
  • 你听说过大数据吧? 什么是大数据呢? 数据看似是冰冷的数字,但是他可能比你想象中更加了解你哟 任何的行为都可以被看...
    豆芽芽_印记阅读 1,924评论 0 1