题意:从给定数组中提取出最长的等差序列(不一定连续),返回它的长度

 

暴力超时:

 1 class Solution {
 2     public int longestSubsequence(int[] arr, int difference) {
 3         int res=1;
 4         for(int i=0;i<arr.length;i++) {
 5             int rei = 1; //初始长度
 6             int temp = arr[i] + difference; //下一个目标值
 7             for (int j = i + 1; j < arr.length; j++) {
 8                 if (arr[j] == temp) { //找到目标值,更新长度和下一个目标值
 9                     rei++;
10                     temp += difference;
11                 }
12             }
13             res = Math.max(rei, res); //更新最大长度
14         }
15         return res;
16     }
17 }

 

动态规划: 每次记录以元素arr[i]为尾的等差序列的长度,在遍历过程中比较记录最大长度

 1 class Solution {
 2     public int longestSubsequence(int[] arr, int difference) {
 3        int res=1;
 4        int[] dp=new int[arr.length];
 5        Map<Integer,Integer> map=new HashMap<>();
 6        for(int val:arr){
 7            int reV=map.getOrDefault(val-difference,0)+1;//不存在返回0
 8            map.put(val,reV);
 9            res=Math.max(res,reV);
10        }
11        return res;
12     }
13 }
posted on 2020-01-03 19:32  Chenjin123  阅读(299)  评论(0编辑  收藏  举报