Skip to content

Instantly share code, notes, and snippets.

@caglarorhan
Created February 2, 2018 21:55
Show Gist options
  • Save caglarorhan/e1ba5488b9ec9fd0805dec071666cc52 to your computer and use it in GitHub Desktop.
Save caglarorhan/e1ba5488b9ec9fd0805dec071666cc52 to your computer and use it in GitHub Desktop.
496. Next Greater Element I -From leetcode
/**
* @param {number[]} findNums
* @param {number[]} nums
* @return {number[]}
*/
var nextGreaterElement = function(findNums, nums) {
const fNLength = findNums.length;
const nLength = nums.length;
let outPut = [];
findNums.forEach(function(i,index){
const numIndex = nums.indexOf(i);
let foundAGreater=false;
for(var it=numIndex+1; it<=nLength; it++){
if(i<nums[it]){ outPut.push(nums[it]); foundAGreater=true; break;}
}
if(!foundAGreater){outPut.push(-1)}
});
return outPut;
};
@caglarorhan
Copy link
Author

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
Note:
All elements in nums1 and nums2 are unique.
The length of both nums1 and nums2 would not exceed 1000.

@jielong39
Copy link

jielong39 commented Sep 2, 2018

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
if subset from index = 1 begin, the position would begin index =1 at the parent set yet,which make output[1] = 3
so,your code var it=numIndex+1,should change to var it=numIndex

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment