[JAVA] Sort and use median / T : Max(O(NLogN + MLogM), O(NM)), S : O(N + M)


  • 0
    J
    public class Solution {
        public int minTotalDistance(int[][] grid) {
            ArrayList<Integer> xs = new ArrayList<Integer>();        
            ArrayList<Integer> ys = new ArrayList<Integer>();
            
            for(int i = 0; i < grid.length; i++) {
                for(int j = 0; j < grid[0].length; j++) {
                    if(grid[i][j] == 1){
                        xs.add(i);
                        ys.add(j);
                    }
                }
            }
            
            Collections.sort(xs);
            Collections.sort(ys);
            
            int x = xs.get(xs.size()/2);
            int y = ys.get(ys.size()/2);
            
            int sum = 0;
            for(int i = 0; i < grid.length; i++) {
                for(int j = 0; j < grid[0].length; j++) {
                    if(grid[i][j] == 1){
                        sum += Math.abs(i - x);
                        sum += Math.abs(j - y);
                    }
                }
            }
            
            
            return sum;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.