446:等差数列划分 II - 子序列

This commit is contained in:
huangge1199 2021-08-11 09:40:57 +08:00
parent f99d54d01e
commit ab9ed7881d
3 changed files with 142 additions and 1 deletions

View File

@ -0,0 +1,90 @@
//给你一个整数数组 nums 返回 nums 中所有 等差子序列 的数目
//
// 如果一个序列中 至少有三个元素 并且任意两个相邻元素之差相同则称该序列为等差序列
//
//
// 例如[1, 3, 5, 7, 9][7, 7, 7, 7] [3, -1, -5, -9] 都是等差序列
// 再例如[1, 1, 2, 5, 7] 不是等差序列
//
//
// 数组中的子序列是从数组中删除一些元素也可能不删除得到的一个序列
//
//
// 例如[2,5,10] [1,2,1,2,4,1,5,10] 的一个子序列
//
//
// 题目数据保证答案是一个 32-bit 整数
//
//
//
// 示例 1
//
//
//输入nums = [2,4,6,8,10]
//输出7
//解释所有的等差子序列为
//[2,4,6]
//[4,6,8]
//[6,8,10]
//[2,4,6,8]
//[4,6,8,10]
//[2,4,6,8,10]
//[2,6,10]
//
//
// 示例 2
//
//
//输入nums = [7,7,7,7,7]
//输出16
//解释数组中的任意子序列都是等差子序列
//
//
//
//
// 提示
//
//
// 1 <= nums.length <= 1000
// -231 <= nums[i] <= 231 - 1
//
// Related Topics 数组 动态规划
// 👍 144 👎 0
package leetcode.editor.cn;
import java.util.HashMap;
import java.util.Map;
//446:等差数列划分 II - 子序列
class ArithmeticSlicesIiSubsequence{
public static void main(String[] args) {
//测试代码
Solution solution = new ArithmeticSlicesIiSubsequence().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int numberOfArithmeticSlices(int[] nums) {
int count = 0;
int length = nums.length;
Map<Long, Integer>[] f = new Map[length];
for (int i = 0; i < length; ++i) {
f[i] = new HashMap<>();
}
for (int i = 0; i < length; ++i) {
for (int j = 0; j < i; ++j) {
long d = (long) nums[i] - nums[j];
int cnt = f[j].getOrDefault(d, 0);
count += cnt;
f[i].put(d, f[i].getOrDefault(d, 0) + cnt + 1);
}
}
return count;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,51 @@
<p>给你一个整数数组 <code>nums</code> ,返回 <code>nums</code> 中所有 <strong>等差子序列</strong> 的数目。</p>
<p>如果一个序列中 <strong>至少有三个元素</strong> ,并且任意两个相邻元素之差相同,则称该序列为等差序列。</p>
<ul>
<li>例如,<code>[1, 3, 5, 7, 9]</code><code>[7, 7, 7, 7]</code><code>[3, -1, -5, -9]</code> 都是等差序列。</li>
<li>再例如,<code>[1, 1, 2, 5, 7]</code> 不是等差序列。</li>
</ul>
<p>数组中的子序列是从数组中删除一些元素(也可能不删除)得到的一个序列。</p>
<ul>
<li>例如,<code>[2,5,10]</code><code>[1,2,1,<em><strong>2</strong></em>,4,1,<strong><em>5</em></strong>,<em><strong>10</strong></em>]</code> 的一个子序列。</li>
</ul>
<p>题目数据保证答案是一个 <strong>32-bit</strong> 整数。</p>
<p>&nbsp;</p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>nums = [2,4,6,8,10]
<strong>输出:</strong>7
<strong>解释:</strong>所有的等差子序列为:
[2,4,6]
[4,6,8]
[6,8,10]
[2,4,6,8]
[4,6,8,10]
[2,4,6,8,10]
[2,6,10]
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>nums = [7,7,7,7,7]
<strong>输出:</strong>16
<strong>解释:</strong>数组中的任意子序列都是等差子序列。
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1&nbsp; &lt;= nums.length &lt;= 1000</code></li>
<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
<div><div>Related Topics</div><div><li>数组</li><li>动态规划</li></div></div>\n<div><li>👍 144</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long