Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit9c3532f

Browse files
[LEET-000] add one more way for Next Greater Element I
1 parent9ddcb69 commit9c3532f

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

‎leetcode-algorithms/src/main/java/com/stevesun/solutions/NextGreaterElementI.java

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
packagecom.stevesun.solutions;
22

3+
importjava.util.HashMap;
4+
importjava.util.Map;
5+
importjava.util.Stack;
6+
37
/**
48
* 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.
59
@@ -24,7 +28,27 @@
2428
*/
2529
publicclassNextGreaterElementI {
2630

27-
publicint[]nextGreaterElement(int[]findNums,int[]nums) {
31+
publicint[]nextGreaterElement_clever_way(int[]findNums,int[]nums) {
32+
Stack<Integer>stack =newStack();
33+
Map<Integer,Integer>map =newHashMap();
34+
for (inti =0;i <nums.length;i++) {
35+
while (!stack.isEmpty() &&nums[i] >stack.peek()) {
36+
map.put(stack.pop(),nums[i]);
37+
}
38+
stack.push(nums[i]);
39+
}
40+
41+
while (!stack.isEmpty())map.put(stack.pop(), -1);
42+
43+
int[]result =newint[findNums.length];
44+
for (inti =0;i <findNums.length;i++) {
45+
result[i] =map.get(findNums[i]);
46+
}
47+
returnresult;
48+
}
49+
50+
51+
publicint[]nextGreaterElement_naive_way(int[]findNums,int[]nums) {
2852
int[]result =newint[findNums.length];
2953
for (inti =0;i <findNums.length;i++) {
3054
booleanfound =false;

‎leetcode-algorithms/src/test/java/com/stevesun/NextGreaterElementITest.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@ public void test1(){
3232
findNums =newint[]{4,1,2};
3333
nums =newint[]{1,3,4,2};
3434
expected =newint[]{-1,3, -1};
35-
actual =test.nextGreaterElement(findNums,nums);
35+
actual =test.nextGreaterElement_naive_way(findNums,nums);
36+
assertArrayEquals(expected,actual);
37+
38+
actual =test.nextGreaterElement_clever_way(findNums,nums);
3639
assertArrayEquals(expected,actual);
3740
}
3841
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp