Advertisement
ogv

Untitled

ogv
Dec 2nd, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. class Solution {
  2. public int[] nextGreaterElements(int[] nums) {
  3. int len = nums.length;
  4. int[] results = new int[len];
  5. Arrays.fill(results, -1);
  6.  
  7. PriorityQueue<Element> waiting = new PriorityQueue<>();
  8. waiting.add(new Element(0, nums[0]));
  9.  
  10. for (int k = 1; k < 2*len; k++) {
  11. Element top = waiting.peek();
  12. if (top.position <= k - len) {
  13. waiting.poll();
  14. top = waiting.peek();
  15. }
  16.  
  17. int current = nums[k >= len ? k-len: k];
  18.  
  19. if (current > top.value) {
  20. for (Element element: waiting) {
  21. int p = element.position;
  22. results[p >= len ? p-len: p] = current;
  23. }
  24.  
  25. waiting.clear();
  26. }
  27.  
  28. waiting.add(new Element(k, current));
  29. }
  30.  
  31. return results;
  32. }
  33.  
  34. private class Element implements Comparable<Element> {
  35. public int position;
  36. public int value;
  37.  
  38. public Element(int position, int value) {
  39. this.position = position;
  40. this.value = value;
  41. }
  42.  
  43. public int compareTo(Element another) {
  44. return value - another.value;
  45. }
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement