动态规划
- 思路:
- 可以参考力扣1218. 最长定差子序列
- 目前不清楚公差,可以将序列最大最小值找到,公差的范围是 [-(max - min), (max - min)],按公差递增迭代遍历求出最长等差数列;
cpp
class Solution {
public:
int longestArithSeqLength(vector<int>& nums) {
auto [minit, maxit] = std::minmax_element(nums.begin(), nums.end());
int diff = *maxit - *minit;
int ans = 0;
for (int d = -diff; d <= diff; ++d) {
std::unordered_map<int, int> dp;
for (int v : nums) {
dp[v] = dp[v - d] + 1;
ans = std::max(ans, dp[v]);
}
}
return ans;
}
};
- 时间复杂度比较高,应该是哈希表频繁插入导致,将 dp 数据结构换成数组,数组下标最大值为元素最大值 + 1;
cpp
class Solution {
public:
int longestArithSeqLength(vector<int>& nums) {
auto [minit, maxit] = std::minmax_element(nums.begin(), nums.end());
int diff = *maxit - *minit;
int ans = 1;
for (int d = -diff; d <= diff; ++d) {
std::vector<int> dp(*maxit + 1, -1);
for (int v : nums) {
int prev = v - d;
// ensure prev is in nums and has exist(or v is the first item)
if (prev >= *minit && prev <= *maxit && dp[prev] != -1) {
dp[v] = std::max(dp[v], dp[prev] + 1);
ans = std::max(ans, dp[v]);
}
dp[v] = std::max(dp[v], 1);
}
}
return ans;
}
};