leetcode吧 关注:1,111贴子:2,374
  • 5回复贴,共1

1027. Longest Arithmetic Sequence 又是数组

只看楼主收藏回复

我一定是miss了什么重要的算法 又被一道题block了
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
给出一个数组中最长的arithmetic子数组的长度。
解释arithmetic
that a sequence B is arithmetic if B[i+1] - B[i] are all the same value
(俺的解释:就是从数组中按顺序挑选出的subarray 不用连续,但是前后不能颠倒。 选出来的元素相邻两个的差都是相等的)
看例子最明白
Input: [3,6,9,12]
Output: 4
Explanation: The whole array is an arithmetic sequence with steps of length = 3.
Input: [9,4,7,2,10]
Output: 3
Explanation: The longest arithmetic subsequence is [4,7,10].
Input: [20,1,15,3,10,5,8]
Output: 4
Explanation: The longest arithmetic subsequence is [20,15,10,5].


IP属地:上海1楼2019-04-24 17:55回复
    这题要用dp 但存的东西比较特别。有点意思


    来自iPhone客户端2楼2019-05-03 02:04
    收起回复
      发一下我写的:
      public int longestArithSeqLength(int[] A) {
      int n=A.length;
      Map<Integer, Integer>[] dp=new HashMap[n];
      int res=2;
      for(int i=0;i<n;i++) {
      Map<Integer, Integer> mi=new HashMap<> ();
      for(int j=0;j<i;j++) {
      Map<Integer, Integer> mj=dp[j];
      int k=A[i]-A[j];
      int val=2;
      if(mj.containsKey(k)) val=mj.get(k)+1;
      if(mi.containsKey(k)) val=Math.max(val, mi.get(k));
      mi.put(k, val);
      res=Math.max(res, mi.get(k));
      }
      dp[i]=mi;
      }
      return res;
      }


      3楼2019-05-04 08:05
      收起回复
        建一个dp数组,数组存的是map。map的key是等差数列的差,value是以数组当前数字结尾,以key为等差的最长数列长度。 循环中注意更新map和最终结果。


        来自iPhone客户端4楼2019-05-08 04:42
        回复