Skip to content
This repository was archived by the owner on Dec 19, 2023. It is now read-only.

Commit df9777e

Browse files
committed
Add problem 496
1 parent 6a5a42e commit df9777e

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

algorithms/496/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
## 496. Next Greater Element I
2+
3+
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`.
4+
5+
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.
6+
7+
**Example 1:**
8+
<pre>
9+
<b>Input:</b> <b>nums1</b> = [4,1,2], <b>nums2</b> = [1,3,4,2].
10+
<b>Output:</b> [-1,3,-1]
11+
<b>Explanation:</b>
12+
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
13+
For number 1 in the first array, the next greater number for it in the second array is 3.
14+
For number 2 in the first array, there is no next greater number for it in the second
15+
array, so output -1.
16+
</pre>
17+
18+
19+
**Example 2:**
20+
<pre>
21+
<b>Input:</b> <b>nums1</b> = [2, 4] <b>nums2</b> = [1,2,3,4].
22+
<b>Output:</b> [3,-1]
23+
<b>Explanation:</b>
24+
For number 2 in the first array, the next greater number for it in the second array is 3.
25+
For number 4 in the first array, there is no next greater number for it in the second
26+
array, so output -1.
27+
</pre>
28+
29+
30+
**Note:**
31+
32+
1. All elements in `nums1` and `nums2` are unique.
33+
2. The length of both `nums1` and `nums2` would not exceed 1000.

algorithms/496/solution.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package main
2+
3+
// Time complexity, O(n*m) where n is the length of the superset
4+
// and m is the length of subset
5+
// Space complexity, O(m)
6+
func nextGreaterElement(nums1 []int, nums2 []int) []int {
7+
res := make([]int, len(nums1))
8+
for i := 0; i < len(nums1); i++ {
9+
for j := 0; ; j++ {
10+
if nums1[i] == nums2[j] {
11+
for j++; j < len(nums2) && nums2[j] < nums1[i]; j++ {
12+
}
13+
if j < len(nums2) {
14+
res[i] = nums2[j]
15+
} else {
16+
res[i] = -1
17+
}
18+
break
19+
}
20+
}
21+
}
22+
return res
23+
}

0 commit comments

Comments
 (0)