|
1 | 1 | class Solution {
|
2 |
| - public int findShortestSubArray(int[] nums) { |
3 |
| - Map<Integer, Entry> map = new HashMap<>(); |
4 |
| - |
5 |
| - for (int i = 0; i < nums.length; i++) { |
6 |
| - if (map.containsKey(nums[i])) { |
7 |
| - map.get(nums[i]).degree++; |
8 |
| - map.get(nums[i]).endIdx = i; |
9 |
| - } |
10 |
| - else { |
11 |
| - map.put(nums[i], new Entry(1, i, i)); |
12 |
| - } |
13 |
| - } |
14 |
| - |
15 |
| - int res = Integer.MAX_VALUE; |
16 |
| - int degree = Integer.MIN_VALUE; |
17 |
| - |
18 |
| - for (Entry entry : map.values()) { |
19 |
| - if (degree < entry.degree) { |
20 |
| - degree = entry.degree; |
21 |
| - res = entry.endIdx - entry.startIdx + 1; |
22 |
| - } |
23 |
| - else if (degree == entry.degree) { |
24 |
| - res = Math.min(entry.endIdx - entry.startIdx + 1, res); |
25 |
| - } |
26 |
| - } |
27 |
| - |
28 |
| - return res; |
| 2 | + public int findShortestSubArray(int[] nums) { |
| 3 | + Map<Integer, Integer> count = new HashMap<>(); |
| 4 | + Map<Integer, Integer> left = new HashMap<>(); |
| 5 | + Map<Integer, Integer> right = new HashMap<>(); |
| 6 | + int degree = 0; |
| 7 | + for (int i = 0; i < nums.length; i++) { |
| 8 | + int num = nums[i]; |
| 9 | + if (!left.containsKey(num)) { |
| 10 | + left.put(num, i); |
| 11 | + } |
| 12 | + right.put(num, i); |
| 13 | + count.put(num, count.getOrDefault(num, 0) + 1); |
| 14 | + degree = Math.max(degree, count.get(num)); |
29 | 15 | }
|
30 |
| - |
31 |
| - class Entry { |
32 |
| - int degree; |
33 |
| - int startIdx; |
34 |
| - int endIdx; |
35 |
| - |
36 |
| - public Entry(int degree, int startIdx, int endIdx) { |
37 |
| - this.degree = degree; |
38 |
| - this.startIdx = startIdx; |
39 |
| - this.endIdx = endIdx; |
40 |
| - } |
| 16 | + int ans = nums.length; |
| 17 | + for (int key : count.keySet()) { |
| 18 | + if (count.get(key) == degree) { |
| 19 | + ans = Math.min(ans, right.get(key) - left.get(key) + 1); |
| 20 | + } |
41 | 21 | }
|
| 22 | + return ans; |
| 23 | + } |
42 | 24 | }
|
0 commit comments