public static void main(String[] args) {
    // TODO code application logic here
    int numRows = 5;
    int numCols = numRows;
    int[][] twoDimArray = new int[numRows][numCols];
    Random randGen = new Random();

    for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numCols; j++) {
            int randIndex = randGen.nextInt(4);
            int value = randGen.nextInt(100);
            twoDimArray[i][j] = value;
        }
    }
    System.out.println("\nThe two-dimensional array: ");
    for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numCols; j++) {
            System.out.print(twoDimArray[i][j] + " ");
        }
        System.out.println();

    }  
    }
}

I want to find a local minimum using a "brute force" approach. I know with a one dimensional array I would use a for-loop to compare all the elements in the array until I found a local minimum, but I don't know how to do that here.

我想找到一个使用“强力”方法的局部最小值。我知道使用一维数组我会使用for循环来比较数组中的所有元素,直到找到局部最小值,但我不知道如何在这里做。

Edit: Could I use binary search instead? Find the middle row and search there and if one isn't found, I search one of the halves.

编辑:我可以使用二进制搜索吗?找到中间行并在那里搜索,如果找不到,我搜索其中一半。

1 个解决方案

#1


1

The brute force method would be very similar to that of a 1D array, just with an extra loop, and a few more checks:

蛮力方法与1D数组非常相似,只需要一个额外的循环,还有一些检查:

public int[] findLocalMinimum(int[][] arr) {
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr[i].length; j++) {

            int current = arr[i][j];

            if (i + 1 < arr.length    && current >= arr[i + 1][j] ||
                i - 1 >= 0            && current >= arr[i - 1][j] ||
                j + 1 < arr[i].length && current >= arr[i][j + 1] ||
                j - 1 >= 0            && current >= arr[i][j - 1]) {
                continue;
            } else {
                return new int[] { i, j };
            }

        }
    }
    return new int[] { -1, -1 };
}

更多相关文章

  1. Java中怎么把字符串数组转为整形数组
  2. 剑指Offer(六)旋转数组的最小数字(Java版 )
  3. Java中double型数组的HashCode产生
  4. java中的成员变量和局部变量的区别
  5. 求助:json + java 返回 数据 数组中去掉双引号
  6. 了解数组类型和使用java.util.Arrays类
  7. java的数组下标的非常严重的问题,异常不爽
  8. java数组常用功能
  9. 对一个JavaScript对象数组进行排序。

随机推荐

  1. Android中Json的解析和构建
  2. Android 10 获取相册图片失败
  3. 【android】通话录音
  4. Android文件列表RecyclerView中点击视频
  5. Android API等级、Android版本、发布日期
  6. Android 9.0 P 状态栏下移的实现
  7. Android 应用Crash 后自动重启
  8. Android: Loading files from the Assets
  9. PULL解析XML
  10. Android 之应用程序重启