1027:最长等差数列

This commit is contained in:
huangge1199 2021-08-10 16:19:00 +08:00
parent 8bd1475a8e
commit c21781366e
2 changed files with 119 additions and 0 deletions

View File

@ -0,0 +1,80 @@
//给定一个整数数组 A返回 A 中最长等差子序列的长度
//
// 回想一下A 的子序列是列表 A[i_1], A[i_2], ..., A[i_k] 其中 0 <= i_1 < i_2 < ... < i_k <= A
//.length - 1并且如果 B[i+1] - B[i]( 0 <= i < B.length - 1) 的值都相同那么序列 B 是等差的
//
//
//
// 示例 1
//
// 输入[3,6,9,12]
//输出4
//解释
//整个数组是公差为 3 的等差数列
//
//
// 示例 2
//
// 输入[9,4,7,2,10]
//输出3
//解释
//最长的等差子序列是 [4,7,10]
//
//
// 示例 3
//
// 输入[20,1,15,3,10,5,8]
//输出4
//解释
//最长的等差子序列是 [20,15,10,5]
//
//
//
//
// 提示
//
//
// 2 <= A.length <= 2000
// 0 <= A[i] <= 10000
//
// Related Topics 数组 哈希表 二分查找 动态规划
// 👍 144 👎 0
package leetcode.editor.cn;
import java.util.Arrays;
//1027:最长等差数列
class LongestArithmeticSubsequence {
public static void main(String[] args) {
//测试代码
Solution solution = new LongestArithmeticSubsequence().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int longestArithSeqLength(int[] nums) {
int max = 0;
for (int num : nums) {
max = Math.max(max, num);
}
int[][] dp = new int[nums.length][max*2+1];
for (int[] t:dp){
Arrays.fill(t,-1);
}
int result = 2;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
int index = nums[i]-nums[j]+max;
dp[i][index]=Math.max(2,dp[j][index]+1);
result = Math.max(result,dp[i][index]);
}
}
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,39 @@
<p>给定一个整数数组&nbsp;<code>A</code>,返回 <code>A</code>&nbsp;中最长等差子序列的<strong>长度</strong></p>
<p>回想一下,<code>A</code>&nbsp;的子序列是列表&nbsp;<code>A[i_1], A[i_2], ..., A[i_k]</code> 其中&nbsp;<code>0 &lt;= i_1 &lt; i_2 &lt; ... &lt; i_k &lt;= A.length - 1</code>。并且如果&nbsp;<code>B[i+1] - B[i]</code>(&nbsp;<code>0 &lt;= i &lt; B.length - 1</code>) 的值都相同,那么序列&nbsp;<code>B</code>&nbsp;是等差的。</p>
<p>&nbsp;</p>
<p><strong>示例 1</strong></p>
<pre><strong>输入:</strong>[3,6,9,12]
<strong>输出:</strong>4
<strong>解释: </strong>
整个数组是公差为 3 的等差数列。
</pre>
<p><strong>示例 2</strong></p>
<pre><strong>输入:</strong>[9,4,7,2,10]
<strong>输出:</strong>3
<strong>解释:</strong>
最长的等差子序列是 [4,7,10]。
</pre>
<p><strong>示例 3</strong></p>
<pre><strong>输入:</strong>[20,1,15,3,10,5,8]
<strong>输出:</strong>4
<strong>解释:</strong>
最长的等差子序列是 [20,15,10,5]。
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ol>
<li><code>2 &lt;= A.length &lt;= 2000</code></li>
<li><code>0 &lt;= A[i] &lt;= 10000</code></li>
</ol>
<div><div>Related Topics</div><div><li>数组</li><li>哈希表</li><li>二分查找</li><li>动态规划</li></div></div>\n<div><li>👍 144</li><li>👎 0</li></div>