您的位置:首页 > 其它

496. Next Greater Element I

2017-12-11 16:25 645 查看

Problem Statement

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:

1. All elements in nums1 and nums2 are unique.

2. The length of both nums1 and nums2 would not exceed 1000.

Thinking

题目的意思是给出两个数组(第一个数组是第二个数组的子串),需要找到num1的每一个元素在num2中对应的位置的右面第一个比他大的元素,不存在则返回-1。

Solution

class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] buff;
buff = new int[nums1.length];
int len_num2 = nums2.length;
for(int i = 0; i < nums1.length;i++){
int tmp = 0;
int loc = find_loc(nums2,nums1[i]);
if(loc != len_num2){
for(int j = loc;j < len_num2;j++){
if(nums2[j] > nums1[i]){
tmp = 1;
buff[i] = nums2[j];
}
if(tmp == 1)
break;
}
if(tmp == 0)
buff[i] = -1;
}
}
return buff;
}
public int find_loc(int[] num,int m){
for(int i = 0;i < num.length;i++){
if(num[i] == m)
return i;
}
return 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: