Brute Force
O(n^2)
- one way to solve circular array is to extend the length of array to twice length
public class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] tmp = new int[nums.length * 2];
int index = 0;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < nums.length; ++j) {
tmp[index++] = nums[j];
}
}
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; ++i) {
int j = i + 1;
while (j < tmp.length && tmp[j] <= nums[i]) {
j++;
}
result[i] = j == tmp.length ? -1 : tmp[j];
}
return result;
}
}
get rid of tmp array
public int[] nextGreaterElements2(int[] nums) {
int n = nums.length;
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = -1;
for (int k = i+1; k < i + n; k++) {
if (nums[k%n] > nums[i]){
res[i] = nums[k%n];
break;
}
}
}
return res;
}
Stack
O(n)
sdf