496. Next Greater Element I
Approach and Solution
We can solve the problem by iterating over nums1 and, for each element in nums1, checking its position in nums2. From that position onward, we look for the next greater element. If we find a larger element, we add it to the result; if not, we append -1.
Here’s the JavaScript code for the solution:
var nextGreaterElement = function(nums1, nums2) {
let result = new Array();
for (let i = 0; i < nums1.length; i++) {
let j = nums2.indexOf(nums1[i]);
result.push(-1);
for (let k = j+1; k < nums2.length; k++){
if (nums2[k] > nums2[j]){
result[i] = nums2[k];
break;
}
}
}
return result;
};
Here’s the Java code for the solution:
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int n1 = nums1.length;
int n2 = nums2.length;
int[] result = new int[n1];
Arrays.fill(result,-1);
int found =0 , i=0,j=0;
for(i=0;i<n1;i++)
{
found = 0;
for(j=0;j<n2;j++)
{
if(nums1[i] == nums2[j]) found = 1;
if(nums2[j] > nums1[i] && found ==1)
{
result[i] = nums2[j];
break;
}
}
}
return result;
}
}
Time Complexity
The time complexity of this approach is O(n * m), where n is the length of nums1 and m is the length of nums2. This is because for each element in nums1, we search for the next greater element by iterating through part of nums2.
Conclusion
This solution is simple to implement and works well for small input sizes. However, for larger inputs, a more optimized approach using a stack could improve the efficiency to O(n + m) by processing nums2 in reverse order. Nevertheless, the current solution is a good start to understanding the problem and the logic behind it.
Comments
Post a Comment