Created
April 19, 2016 00:49
-
-
Save cangoal/dbe99965676ce72824323196ce687227 to your computer and use it in GitHub Desktop.
LeetCode - Best Meeting Point
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|. | |
// For example, given three people living at (0,0), (0,4), and (2,2): | |
// 1 - 0 - 0 - 0 - 1 | |
// | | | | | | |
// 0 - 0 - 0 - 0 - 0 | |
// | | | | | | |
// 0 - 0 - 1 - 0 - 0 | |
// The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6. | |
// find the median | |
public int minTotalDistance(int[][] grid) { | |
if(grid == null || grid.length == 0 || grid[0].length == 0) return 0; | |
List<Integer> rows = new ArrayList<Integer>(); | |
List<Integer> cols = 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){ | |
rows.add(i); | |
cols.add(j); | |
} | |
} | |
} | |
Collections.sort(cols); | |
return getMinDistance(rows, rows.get(rows.size() / 2)) + getMinDistance(cols, cols.get(cols.size() / 2)); | |
} | |
private int getMinDistance(List<Integer> lst, int origin){ | |
int res = 0; | |
for(int num : lst){ | |
res += Math.abs(num - origin); | |
} | |
return res; | |
} | |
// without the median | |
public int minTotalDistance(int[][] grid) { | |
if(grid == null || grid.length == 0 || grid[0].length == 0) return 0; | |
List<Integer> rows = new ArrayList<Integer>(); | |
List<Integer> cols = 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){ | |
rows.add(i); | |
cols.add(j); | |
} | |
} | |
} | |
Collections.sort(cols); | |
return getMinDistance(rows) + getMinDistance(cols); | |
} | |
private int getMinDistance(List<Integer> lst){ | |
int res = 0, left = 0, right = lst.size() - 1; | |
while(left < right){ | |
res += lst.get(right--) - lst.get(left++); | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment