Share the joy
This is eveolved from 1D problem – find local min.
I would say this is a interesting problem and hvae great solution. The definition of “local” is near elements, ans in same row or column.
There is junmin’s implementation, link , which is similar to mine. And another very clear material from mit, link.
- package weeklychallenge3;
- import java.util.Arrays;
- public class PeakInMatrix {
- public static void main(String[] args) {
- int[][] matrix = {
- { 9, 3, 5, 2, 4, 9, 8 },
- { 7, 2, 5, 1, 4, 0, 3 },
- { 9, 8, 2, 3, 4, 4, 8 },
- { 7, 6, 3, 1, 3, 2, 3 },
- { 9, 0, 6, 0, 4, 6, 4 },
- { 9, 7, 8, 0, 5, 3, 0 },
- { 2, 1, 2, 1, 1, 1, 1 }
- };
- int[] result = findPeakInMatrix(matrix);
- System.out.println(Arrays.toString(result));
- }
- public static int[] findPeakInMatrix(int[][] matrix) {
- if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
- return null;
- }
- int leftCol = 0, rightCol = matrix[0].length, totalRow = matrix.length, totalCol = matrix[0].length;
- int midCol = 0, maxIndex = 0;
- while (leftCol <= rightCol) {
- midCol = (leftCol + rightCol) >> 1;
- maxIndex = 0;
- for (int i = 1; i < totalRow; i++) {
- maxIndex = (matrix[i][midCol] > matrix[maxIndex][midCol]) ? i : maxIndex;
- }
- if (midCol – 1 >= 0 && matrix[maxIndex][midCol – 1] > matrix[maxIndex][midCol]) {
- rightCol = midCol;
- } else if (midCol + 1 < totalCol && matrix[maxIndex][midCol + 1] > matrix[maxIndex][midCol]) {
- leftCol = midCol;
- } else {
- break;
- }
- }
- return new int[] { maxIndex, midCol };
- }
- }