Interview - Find magnitude pole in an array

前端 未结 8 2250
孤独总比滥情好
孤独总比滥情好 2021-02-09 15:52

Magnitude Pole: An element in an array whose left hand side elements are lesser than or equal to it and whose right hand side element are greater than or equal to it.

相关标签:
8条回答
  • 2021-02-09 16:40
    • Create two bool[N] called NorthPole and SouthPole (just to be humorous.
    • step forward through A[]tracking maximum element found so far, and set SouthPole[i] true if A[i] > Max(A[0..i-1])
    • step backward through A[] and set NorthPole[i] true if A[i] < Min(A[i+1..N-1)
    • step forward through NorthPole and SouthPole to find first element with both set true.

    O(N) in each step above, as visiting each node once, so O(N) overall.

    0 讨论(0)
  • 2021-02-09 16:41

    Java implementation:

    Collection<Integer> magnitudes(int[] A) {
        int length = A.length;
        // what's the maximum number from the beginning of the array till the current position
        int[] maxes = new int[A.length];
        // what's the minimum number from the current position till the end of the array
        int[] mins = new int[A.length];
    
        // build mins
        int min = mins[length - 1] = A[length - 1];
        for (int i = length - 2; i >= 0; i--) {
            if (A[i] < min) {
                min = A[i];
            }
            mins[i] = min;
        }
    
        // build maxes
        int max = maxes[0] = A[0];
        for (int i = 1; i < length; i++) {
            if (A[i] > max) {
                max = A[i];
            }
            maxes[i] = max;
        }
    
        Collection<Integer> result = new ArrayList<>();
        // use them to find the magnitudes if any exists
        for (int i = 0; i < length; i++) {
            if (A[i] >= maxes[i] && A[i] <= mins[i]) {
                // return here if first one only is needed
                result.add(A[i]);
            }
        }
        return result;
    }
    
    0 讨论(0)
提交回复
热议问题