首页 > 技术文章 > 【leetcode】496. Next Greater Element I

magicya 2017-04-12 23:14 原文

要求:给出两个数组(没有重复的)nums1和nums2,其中nums1的元素是nums2的子集。 查找nums2的相应位置中nums1元素的所有下一个更大的数字。

nums1中的下一个大数字x的数字是num2中右边的第一个较大的数字。 如果不存在,则输出-1表示该数字。

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]

代码很臃肿但是执行效率还是不错的....
 1 public class Solution {
 2     public int[] nextGreaterElement(int[] findNums, int[] nums) {
 3         int len = findNums.length;      //findNums 的长度 赋值给 len 
 4         int [] result = new int [len];  //创建一个和findNum 等长的数组
 5         
 6         for(int i = 0; i < len; i++){  
 7             int t1 = findNums[i];
 8             int tag = check(t1,nums);
 9             
10             if(tag == nums.length-1){
11                 result[i] = -1;
12                 continue;
13             }
14             
15             for(int j = tag+1; j < nums.length;j++){
16                 if(t1 < nums[j]){
17                     result[i] = nums[j];
18                      break; 
19                 }
20                 result[i] = -1;
21             }
22        }   
23         return result;
24     }
25     
26     //获取数组中目标元素的下标(第一个)
27     public int check(int x,int [] array){
28         for(int i = 0;i < array.length;i++){
29             if(array[i] == x){
30                 return i;
31             }
32         }
33         return -1;
34     }
35 }

 

推荐阅读