class Solution {
public int[] nextGreaterElement(int[] nums1
, int[] nums2
) {
int[] result
=new int[nums1
.length
];
Map
<Integer,Integer> map
=new HashMap<>();
for(int i
=0;i
<nums2
.length
;i
++){
map
.put(nums2
[i
],i
);
}
for(int i
=0;i
<nums1
.length
;i
++){
int index
=map
.get(nums1
[i
]);
if(index
==nums2
.length
-1)
result
[i
]=-1;
for(int j
=index
+1;j
<nums2
.length
;j
++){
if(nums2
[j
]>nums2
[index
]){
result
[i
]=nums2
[j
];
break;
}
if(j
==nums2
.length
-1)
result
[i
]=-1;
}
}
return result
;
}
}
评论区高赞解法:
将nums2中的每个元素作为键,后面第一个比他大的元素作为值(利用栈找),存入hashmap中,之后遍历nums1就可直接找到答案
转载请注明原文地址: https://mac.8miu.com/read-501251.html