题目
解题思路
- 哈希表
- 滑动窗口
数组的子序列是一个由数组派生出来的序列,它可以通过删除一些元素或不删除元素、且不改变其余元素的顺序而得到。
public int findLHS(int[] nums) {/**将之存在map中,如果存在差是1,则是临近的两个值的出现次数加和*/int max = 0;HashMap<Integer,Integer> map = new HashMap<>();for(int i = 0; i < nums.length; i++) {map.put(nums[i],map.getOrDefault(nums[i],0) + 1);}for(Integer key : map.keySet() ) {if(map.containsKey(key - 1)) {max = Math.max(map.get(key - 1) + map.get(key), max);}if(map.containsKey(key + 1) ) {max = Math.max(max, map.get(key) + map.get(key + 1) );}}return max;}
class Solution {public int findLHS(int[] nums) {//排序Arrays.sort(nums);//左指针int left = 0;//最大值int max = 0;for(int right = 0; right < nums.length; right ++) {while( nums[right] - nums[left] > 1) left++; //前面已经排好序,故当不符合时,更新窗口左边界if(nums[right] - nums[left] == 1) { //最大值减去最小值为1max = Math.max(max,right - left + 1); // 记录此时的最大次数}}return max;}}
