Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Given an array of integers A
, returns A
the longest sequence of arithmetic length .
Recall that A
the sequence is a list of A[i_1], A[i_2], ..., A[i_k]
where 0 <= i_1 < i_2 < ... < i_k <= A.length - 1
. If B[i+1] - B[i]
( 0 <= i < B.length - 1
) values are identical, then the sequence B
is the arithmetic.
Example 1:
Input: [3,6,9,12] Output: 4 explained: the entire array 3 is tolerance of arithmetic series.
Example 2:
Input: [9,4,7,2,10] Output: 3 Explanation: longest arithmetic sequence is [7, 10].
Example 3:
Input: [20,1,15,3,10,5,8] Output: 4 explained: the longest arithmetic sequence is [20,15,10,5].
prompt:
2 <= A.length <= 2000
0 <= A[i] <= 10000
Ideas: In each position A, maintaining a mapping relation map, the former represents the difference, which represents the number of columns the number of arithmetic; when there is more A [i] minus the current A [J] in when the current map, then at position i, the corresponding number plus 1 diff it.
C++
class Solution {
public:
int longestArithSeqLength(vector<int>& A)
{
int n=A.size();
int res=0;
if(0==n)
{
return 0;
}
vector<map<int,int>> tmp(n);
for(int i=0;i<n;i++)
{
for(int j=0;j<i;j++)
{
int diff=A[i]-A[j];
if(tmp[j][diff])
{
tmp[i][diff]=tmp[j][diff]+1;
}
else
{
tmp[i][diff]=2;
}
res=max(res,tmp[i][diff]);
}
}
return res;
}
};
python
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
n=len(A)
if 0==n:
return 0
res=0
tmp=[{} for i in range(n)]
for i in range(n):
for j in range(0,i):
diff=A[i]-A[j]
if diff in tmp[j]:
tmp[i][diff]=tmp[j][diff]+1
else:
tmp[i][diff]=2
res=max(res,tmp[i][diff])
return res