-
SLPH栈(时间复杂度 O(n)):
class Solution(object): def nextGreaterElements(self, nums): """ :type nums: List[int] :rtype: List[int] """ stack = [] size = len(nums) ans = [-1] * size for x in range(size * 2): i = x % size while stack and nums[stack[-1]] < nums[i]: ans[stack.pop()] = nums[i] stack.append(i) return ans
-
SLPH朴素解法(时间复杂度 O(n^2)):
public class Solution { public int[] nextGreaterElements(int[] nums) { int size = nums.length; int[] ans = new int[size]; Arrays.fill(ans, -1); for (int i = 0; i < size; i++) { for (int j = i + 1; j % size != i; j++) { if (nums[j % size] > nums[i]) { ans[i] = nums[j % size]; break; } } } return ans; } }
-