码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】496. Next Greater Element I

时间:2017-04-13 00:43:44      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:class   重复   tco   log   out   amp   数字   第一个   个数   

要求:给出两个数组(没有重复的)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 }

 

【leetcode】496. Next Greater Element I

标签:class   重复   tco   log   out   amp   数字   第一个   个数   

原文地址:http://www.cnblogs.com/magicya/p/6701909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!