1 package solution45;
2 import java.util.*;
3 class Solution {
4 public int solution(int n, int[] nums) {
5 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
6 int maxVal = 0;
7 for (int i = 0; i < n; i++) {
8 int cur = nums[i];
9 for (int j = -1; j <= 1; j++) {
10 int val = cur + j;
11 if (!map.containsKey(val)) {
12 map.put(val, 1);
13 maxVal = Math.max(maxVal, 1);
14 } else {
15 int newval = map.get(val) + 1;
16 map.put(val, newval);
17 maxVal = Math.max(maxVal, newval);
18 }
19 }
20 }
21 return maxVal;
22 }
23 }
算法思路:hash。
来源:https://www.cnblogs.com/asenyang/p/12432422.html