In an unsorted array, replace every element by the first larger element to the right

前端 未结 2 1934
攒了一身酷
攒了一身酷 2020-12-28 20:39

In an unsorted array, we have to replace every element by the first element to the right that is larger than the current element. If none of the elements to the right are b

2条回答
  •  时光取名叫无心
    2020-12-28 21:00

    you can use a stack and the time complexity is O(N).

    algo: Start from the left side and move towards right. When you pick an element form the array (lets say x) pop the stack till the elements from stack (lets say y ) has element greater than the array element i.e. x> y. Than push the element i.e. x to stack.

    e.g. {40,50,11,32,55,68,75} . here s is stack.

    40, as s is empty push it. s: 40

    50, as s.peek() < 50 so pop 40 (40's greater element is 50) than push 50. s: 50

    Next higher element of 40 - 50.

    11, s.peek() > 11 so push 11. s: 50, 11

    32, s.peek() < 32, so pop the element and now it's 50 which is greater than 32 hence push 32. s: 50 ,32

    Next higher element of 11 - 32.

    55, s.peek() < 55, so pop the element i.e. 32 than pop next as well as 50 < 55, than push 55. s: 55.

    Next higher element of 32 - 55.

    Next higher element of 50 - 55.

    68, s.peek() < 68 so pop it and push 68. s: 68

    75, s.peek() < 75 so pop it and push 75 s:75.

    Next higher element of 68 - 75.

    As the array does not have any element no just pop the stack say that for all the elements inside the array does not have greater element i.e. -1.

    Next higher element of 75 - -1.

    The same algo in code:

    public static void fun(int[] a) {
        Stack s = new Stack();
        s.push(a[0]);
    
        for (int i = 1; i < a.length; i++) {
            if (s.peek() != null) {
                while (true) {
                    if (s.peek() == null || s.peek() > a[i]) {
                        break;
                    }
                    System.out.println(s.pop() + ":" + a[i]);
                }
            }
            s.push(a[i]);
        }
        while (s.peek() != null) {
            System.out.println(s.pop() + ":" + -1);
        }
    }
    

提交回复
热议问题