korobushk

stackPreviousGreaterElement

Apr 16th, 2021
912
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package previousgreaterelement;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Stack;
  5.  
  6. public class App {
  7.     public static void main(String[] args) {
  8.         int arr[] = {15, 10, 18, 12, 4, 6, 2, 8};
  9.  
  10.         System.out.println(Arrays.toString(prevGreater(arr)));
  11.     }
  12.  
  13.     public static int[] prevGreater(int[] arr) {
  14. //        int arr[] = {15, 10, 18, 12, 4, 6, 2, 8};
  15.         int[] a = new int[arr.length];
  16.         Stack<Integer> stack = new Stack<>();
  17.         stack.push(arr[0]);
  18.         a[0] = -1;
  19.         for (int i = 1; i < arr.length; i++) {
  20.             while (!stack.isEmpty() &&              //15 10
  21.                     stack.peek() <= arr[i]) {
  22.  
  23.                 stack.pop();                        //_
  24.             }
  25.            
  26.             if (stack.isEmpty())
  27.                 a[i] = -1;                           //-1
  28.             else
  29.                 a[i] = stack.peek();
  30.  
  31.             stack.push(arr[i]);
  32.         }
  33.  
  34.         return a;
  35.     }
  36.  
  37.  
  38. }
  39.  
  40.         //NORMAL SOLUTION slow         
  41.  
  42. //        int[] a = new int[arr.length];
  43. //        a[0]=-1;
  44. //        for (int i = 0; i < arr.length; i++) {
  45. //
  46. //            for (int j = i; j >= 0; j--) {
  47. //                if (arr[i] < arr[j]) {
  48. //                    a[i] = arr[j];
  49. //                    break;
  50. //                } else {
  51. //                    a[i] = -1;
  52. //                }
  53. //            }
  54.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×