• 1218. 最长定差子序列(动态规划)


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

    暴力超时:

     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 }
  • 相关阅读:
    GCC默认的标准不是ANSI C,而是GNU C90
    C/C++预定义宏
    GCC对C标准的支持
    Tupper's selfreferential formula
    VC++对C标准的支持
    一道笔试题
    C语言标准
    FLVPlayback视频
    getDefinitionByName与ApplicationDomain.getDefinition
    SVN
  • 原文地址:https://www.cnblogs.com/NiBosS/p/12145699.html
Copyright © 2020-2023  润新知