quesion:
Analysis:
Two methods:
- brute force:
- find the poistion of each element of nums1 in nums2
- search nums2 until find, or set as -1
- time complexity O(nm), space O(m)
- stack ,hashmap
- fInd each NEXT GREATER of nums2 by using stack, and then store the result in HashMap
– while stack is not empty, pop until stack.peek() >nums2[]
– if stack is empty , put -1 in the HashMap
– if stack is not empty and peek() >nums2[], put nums2[*] into hashmap - extract the NEXT GREATER for nums1 from HashMap
Code
class solution1{
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] res = new int[nums1.length];
Arrays.fill(res, -1);
for (int i=0; i<nums1.length; i++) {
for (int j=findIndex(nums2, nums1[i])+1; j<nums2.length; j++) {
if (nums2[j] > nums1[i]){
res[i] = nums2[j];
break;
}
}
}
return res;
}
// this function will return the position of key in nums
public int findIndex(int[] nums, int key) {
int res = -1;
for (int i=0; i<nums.length; i++) {
if (nums[i] == key) {
res = i;
}
}
return res;
}
public int[] nextGreaterElement1(int[] nums1, int[] nums2) {
int[] res = new int[nums1.length];
Arrays.fill(res, -1);
for (int i=0; i< nums1.length; i++) {
boolean found = false;
int j = 0;
for (; j<nums2.length; j++) {
if (nums2[j] == nums1[i]) {
found = true;
}
if (found && nums2[j] > nums1[i] ) {
res[i] = nums2[j];
break;
}
if (j == nums2.length) {
res[i] = -1;
}
}
}
return res;
}
public int[] nextGreaterElement2(int[] nums1, int[] nums2) {
int[] res = new int[nums1.length];
HashMap<Integer, Integer> map = new HashMap<>();
Stack<Integer> stack = new Stack<>();
for (int j=nums2.length-1; j>=0; j--) {
while(!stack.isEmpty() && nums2[j] > stack.peek()) {
stack.pop();
}
if (stack.isEmpty()) {
map.put(nums2[j], -1);
}else {
map.put(nums2[j], stack.peek());
}
stack.push(nums2[j]);
}
for (int i=0; i<nums1.length; i++) {
res[i] = map.get(nums1[i]);
}
return res;
}
}