8.15 - hard - 55

296. Best Meeting Point

把两个坐标拆分放入rows,cols,然后求median就是中位数就是要聚会的坐标。证明在这里:https://leetcode.com/problems/best-meeting-point/discuss/

class Solution(object):
    def minTotalDistance(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        rows = []
        cols = []
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == 1:
                    rows.append(i)
                    cols.append(j)
        
        rows = sorted(rows)
        cols = sorted(cols)
        
        x, y = [rows[len(rows)/2], cols[len(cols)/2]]
        
        res = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == 1:
                    res += abs(i-x) + abs(j-y)
        return res

你可能感兴趣的:(8.15 - hard - 55)