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

Appearance settings

Latest commit

 

History

History
History
31 lines (25 loc) · 839 Bytes

File metadata and controls

31 lines (25 loc) · 839 Bytes
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.HashMap;
/**
* 这题和sliding window较类似
* 意思是给定一个数组,找出其中的一个最长的连续子数组,只能有两个不同的数
*/
public class FruitIntoBaskets {
public static int totalFruit(int[] tree) {
int max = 0;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0, j = 0; j < tree.length; j++) {
int value = tree[j];
map.put(value, map.getOrDefault(value, 0) + 1);
for ( ; map.size() > 2; i++) {
int val = tree[i], cnt = map.get(val);
if (cnt == 1) {
map.remove(val);
} else {
map.put(val, cnt - 1);
}
}
max = Math.max(max, j - i + 1);
}
return max;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.