1027. Longest Arithmetic Sequence 又是数组
leetcode吧
全部回复
仅看楼主
level 6
milk_bread 楼主
我一定是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].
2019年04月24日 09点04分 1
level 13
这题要用dp 但存的东西比较特别。有点意思
2019年05月02日 18点05分 2
谢谢 03 每次你出现我就看到了曙光。
2019年05月07日 10点05分
level 13
发一下我写的:
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;
}
2019年05月04日 00点05分 3
让我慢慢研读。第一轮表示没看懂。
2019年05月07日 10点05分
level 13
建一个dp数组,数组存的是map。map的key是等差数列的差,value是以数组当前数字结尾,以key为等差的最长数列长度。 循环中注意更新map和最终结果。
2019年05月07日 20点05分 4
1