496. Next Greater Element I
- Total Accepted: 26241
- Total Submissions: 45724
- Difficulty: Easy
- Contributors:
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
andnums2
are unique. - The length of both
nums1
andnums2
would not exceed 1000.
Subscribe to see which companies asked this question.
题意:
数组1是数组2的子集,遍历数组1中的每一个数,找到在数组2中对应的位置,然后向右寻找一个比它大的数,如果没有则返回-1.
算法思路:
遍历数组1中的每一个数,先寻找数组二中对应的位置,记录在k中,内层循环从k+1开始,返回第一个比数组1中数大的数,否则返回-1
注意的是因为数组的大小不确定, 要使用ArrayList,在转为int[]时,不能直接转化,要进行遍历赋值list.get
代码:
package easy;
import java.util.ArrayList;
public class NextGreaterElement1 {
public static int[] nextGreaterElement(int[] findNums, int[] nums) {
ArrayList list = new ArrayList();
boolean flag = false;
for(int i=0; i<findNums.length; i++){
flag = false;
int k = 0;
//找到第一个数组中的数字对应数组二中的位置
for(int t=0; t<nums.length; t++){
if(nums[t] == findNums[i]){
k = t;
break;
}
}
//寻找greater数
for(int j=k; j<nums.length; j++){
if(nums[j] > findNums[i]){
list.add(nums[j]);
flag = true;
break;
}
}
if(!flag){
list.add(-1);
}
}
int[] result = new int[list.size()];
for(int i=0; i<list.size(); i++){
result[i] = (int)list.get(i);
}
return result;
}
public static void main(String[] args){
int[] num1 = {4,1,2};
int[] num2 = {1,3,4,2};
int[] result = nextGreaterElement(num1, num2);
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
}
}