美文网首页计算机Leetcode, again
Leetcode - Best Meeting Point

Leetcode - Best Meeting Point

作者: Richardo92 | 来源:发表于2016-10-09 05:10 被阅读29次

    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 - Best Meeting Point

        本文链接:https://www.haomeiwen.com/subject/jkjpyttx.html