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;
}
}

本文探讨了在两个数组中,对于nums1中的每个元素,找到它在nums2中的下一个更大的元素的问题。提供了两种解决方案:暴力搜索和使用栈与哈希表的方法。前者时间复杂度为O(nm),后者通过预处理nums2的下一个更大元素,优化至O(n)。代码实现包括遍历查找和栈辅助的哈希表映射。
364

被折叠的 条评论
为什么被折叠?



