题目描述
给你一个整数数组 arr 和一个整数 difference,请你找出 arr 中所有相邻元素之间的差等于给定 difference 的等差子序列,并返回其中最长的等差子序列的长度。
示例:
输入:arr = [1,5,7,8,5,3,4,2,1], difference = -2
输出:4
解释:最长的等差子序列是 [7,5,3,1]。
总结
淦,看了评论说map,但也没有想出来,没想到最后map的方法也是这么高的空间复杂度出来的。
不管思考到了什么阶段,还是 先实现,再优化。
DC:不能AC,超时了。
Sample & Demo Code
class Solution {
public int longestSubsequence(int[] arr, int difference) {
Map<Integer, Integer> map = new HashMap<>();
int res = 0;
for(int a : arr) {
map.put(a, map.getOrDefault(a-difference, 0)+1);
res = Math.max(res, map.get(a));
}
return res;
}
}
Demo Code
class Solution {
public int longestSubsequence(int[] arr, int difference) {
if(arr.length < 2) return 0;
int[] visited = new int[arr.length];
int res = 1;
for(int i = 0; i < arr.length; i++) {
if(visited[i] == 1) continue;
int temp = 1;
int cur = arr[i];
for(int j = i+1; j < arr.length; j++) {
if(arr[j] - cur == difference) {
visited[j] = 1;
temp++;
if(i+temp >= arr.length) return Math.max(res, temp);
cur = arr[j];
}
}
res = Math.max(res, temp);
}
return res;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-arithmetic-subsequence-of-given-difference