題目
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.
思路
題目大意:
給定兩個數(shù)組(無重復(fù))nums1 與 nums2,其中nums1的元素是nums2的子集。在nums2中尋找大于nums1中對應(yīng)位置且距離最近的元素。如果對應(yīng)位置不存在這樣的元素,則輸出-1。
注意:
- nums1與nums2中的所有元素都是唯一的。
- nums1與nums2的元素個數(shù)不超過1000。
代碼
nextGreaterElement.go
package _496_Next_Greater_Element_I
func NextGreaterElement(findNums []int, nums []int) []int {
var ret []int
var numsMap map[int]int
numsLen := len(nums)
numsMap = make(map[int]int, numsLen)
for i := 0; i < numsLen; i++ {
numsMap[nums[i]] = i
}
findNumsLen := len(findNums)
for i := 0; i < findNumsLen; i++ {
num := findNums[i]
pos, _ := numsMap[num]
var ok bool
for j := pos; j < numsLen; j++ {
if nums[j] > num {
ret = append(ret, nums[j])
ok = true
break
}
}
if !ok {
ret = append(ret, -1)
}
}
return ret
}
測試代碼
nextGreaterElement_test.go
package _496_Next_Greater_Element_I
import "testing"
func isSliceEqual(ret, want []int) bool {
len1 := len(ret)
len2 := len(want)
if len1 != len2 {
return false
}
for i := 0; i < len1; i++ {
if ret[i] != want[i] {
return false
}
}
return true
}
func TestNextGreaterElement(t *testing.T) {
nums1, nums2 := []int{4,1,2}, []int{1,3,4,2}
want := []int{-1,3,-1}
ret := NextGreaterElement(nums1, nums2)
if isSliceEqual(ret, want) {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", want, ret)
}
}
func TestNextGreaterElement2(t *testing.T) {
nums1, nums2 := []int{2,4}, []int{1,2,3,4}
want := []int{3,-1}
ret := NextGreaterElement(nums1, nums2)
if isSliceEqual(ret, want) {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", want, ret)
}
}