您的位置:首页 > 其它

496. Next Greater Element I

2017-02-20 15:15 351 查看
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]
//answer1
public class Solution {
public int[] nextGreaterElement(int[] findNums, int[] nums) {
if(findNums == null ||  nums == null ||
findNums.length == 0 || nums.length == 0 ||
findNums.length > nums.length) return new int[0];

int m = findNums.length;
int n = nums.length;
int[] result = new int[m];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();

for(int j = 0; j < n; ++j){
map.put(nums[j], j);
}
for(int i = 0; i < m; ++i){
int j = map.get(findNums[i]);
for(; j < n; ++j){
if(nums[j] > findNums[i]) break;
}
result[i] = j < n ? nums[j] : -1;
}
return result;
}
}
//answer2
public class Solution {
public int[] nextGreaterElement(int[] findNums, int[] nums) {
int i,j,k;
for(i=0;i<findNums.length;i++)
{
for(j=0;j<nums.length;j++)
{
if(findNums[i]==nums[j])
{
for(k=j+1;k<nums.length;k++)
{
if(nums[k]>findNums[i])
{
findNums[i]=nums[k];
break;
}
}
if(k==nums.length)
{
findNums[i]=-1;
}
break;
}
}
}
return findNums;
}
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: