查找比以前更大的数组元素

时间:2014-05-04 08:48:58

标签: arrays

问:我一直在努力解决。 给定阵列:1 2 2 4 4 6 5 4 5 7 8 9 11 13 找到比前面所有元素都大且比前面所有元素都小的第一个元素。 我的想法是对数组进行排序,然后找到第一个未在数组中更改其原始位置的元素。 你怎么看?谁有更好的方法?

有没有办法在O(N^2)以内完成?

感谢

3 个答案:

答案 0 :(得分:7)

  1. 从左向右扫描,跟踪当前最大值。标记当前最大值的任何元素。
  2. 从右向左扫描,跟踪当前最小值。还跟踪当前最左边标记的元素,也是当前最小值。
  3. (感谢@Konstantinos对以下评论中的建议优化。)

    步骤1找到满足第一个标准的所有元素,类似于步骤2.整个事物在时间和空间上都是O(n)。

答案 1 :(得分:0)

根据@ Oli的解决方案:

public static void getElement(int[] array) {
    int n = array.length;
    boolean[] maxis = new boolean[n];
    //compute max
    int max = array[0];
    maxis[0] = true;
    for (int i = 1; i < n; i++) {
        if (array[i] > max) {
            max = array[i];
            maxis[i] = true;
        }
    }
    //initialize requestedNumber, if we get -1 as a reply there is no solution
    int requestedPos = -1;
    int requestedNumber = 0;


    int min = array[n-1];
    if (maxis[n-1]) {
        requestedPos = n-1;
        requestedNumber = min;
    }

    //compute min
    //keep track of current requestedNumber
    for (int i = n - 1 ; i >= 0; i--) {
        if (array[i] < min) {
            min = array[i];
            if (maxis[i]) {
                requestedPos = i;
                requestedNumber = min;
            }
        }
    }


    System.out.println(requestedPos);
    System.out.println(requestedNumber);
}

答案 2 :(得分:0)

我认为有一种更快的方法,无需额外的阵列或标记。

我们只需要一次全表扫描,仅此而已,显然是O(n):

public static void getFirstMinMaxElement(int[] array) {
    //compute max
    int max = array[0];
    int requestedPos = 0; //position
    int requestedNumber = max; //current
    for (int i = 1; i < array.length; i++) {
        if (array[i] > max) {
            max = array[i];
            //only assign a new requested value if there isn't any
            if (requestedPos == -1) {
                requestedPos = i;
                requestedNumber = max;
            }
        }
        //delete current requestedNumber when you find a smaller one
        //use < instead of <= if you don't care about equal elements 
        else if (array[i] <= requestedNumber) {
            requestedPos = -1;
        }
    }
    System.out.println(requestedPos); //if -1, then there is no solution
    System.out.println(requestedNumber);
}