Skip to content

Commit 3140945

Browse files
committed
6/1
1 parent 3dd2830 commit 3140945

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
Easy Leetcode 1464
2+
tags: Array
3+
4+
方法1:
5+
题目不难依旧是自己的思路没有用任何数据结构单纯array操作的话效率最快
6+
方法2
7+
priorityqueue
8+
方法3
9+
TreeMap
10+
11+
12+
```
13+
14+
/*
15+
方法1
16+
*/
17+
//import java.util.stream.IntStream;
18+
public int maxProduct(int[] nums) {
19+
int max, max2nd;
20+
max = max2nd = Integer.MIN_VALUE;
21+
for (int num : nums) {
22+
if (num >= max) {
23+
max2nd = max;
24+
max = num;
25+
} else if (num >= max2nd) {
26+
max2nd = num;
27+
}
28+
}
29+
return (max -1 ) * (max2nd -1);
30+
}
31+
32+
33+
/*
34+
方法2
35+
*/
36+
public int maxProduct(int[] nums) {
37+
PriorityQueue<Integer> max = new PriorityQueue<>(Collections.reverseOrder());
38+
for(int num: nums) max.offer(num);
39+
// pop up the max number to get 2nd max
40+
return (max.poll() -1) * (max.poll() -1);
41+
}
42+
43+
/*
44+
方法3
45+
*/
46+
public int maxProduct(int[] nums) {
47+
TreeMap<Integer, Integer> map = new TreeMap<>();
48+
// save how many times the number appears in the array. you will see why right now
49+
for (int i = 0; i < nums.length; i++) map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
50+
if(map.get(map.lastKey()) >= 2) {
51+
return (map.lastKey() -1) * (map.lastKey() -1);
52+
}else{
53+
// pop up the max number to get 2nd max
54+
int max = map.lastKey() -1;
55+
map.remove(map.lastKey());
56+
return (max * (map.lastKey() -1));
57+
}
58+
}
59+
60+

0 commit comments

Comments
 (0)