-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path2831.找出最长等值子数组.java
97 lines (88 loc) · 2.52 KB
/
2831.找出最长等值子数组.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* @lc app=leetcode.cn id=2831 lang=java
*
* [2831] 找出最长等值子数组
*
* https://leetcode.cn/problems/find-the-longest-equal-subarray/description/
*
* algorithms
* Medium (41.16%)
* Likes: 60
* Dislikes: 0
* Total Accepted: 8.3K
* Total Submissions: 18K
* Testcase Example: '[1,3,2,3,1,3]\n3'
*
* 给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。
*
* 如果子数组中所有元素都相等,则认为子数组是一个 等值子数组 。注意,空数组是 等值子数组 。
*
* 从 nums 中删除最多 k 个元素后,返回可能的最长等值子数组的长度。
*
* 子数组 是数组中一个连续且可能为空的元素序列。
*
*
*
* 示例 1:
*
*
* 输入:nums = [1,3,2,3,1,3], k = 3
* 输出:3
* 解释:最优的方案是删除下标 2 和下标 4 的元素。
* 删除后,nums 等于 [1, 3, 3, 3] 。
* 最长等值子数组从 i = 1 开始到 j = 3 结束,长度等于 3 。
* 可以证明无法创建更长的等值子数组。
*
*
* 示例 2:
*
*
* 输入:nums = [1,1,2,2,1,1], k = 2
* 输出:4
* 解释:最优的方案是删除下标 2 和下标 3 的元素。
* 删除后,nums 等于 [1, 1, 1, 1] 。
* 数组自身就是等值子数组,长度等于 4 。
* 可以证明无法创建更长的等值子数组。
*
*
*
*
* 提示:
*
*
* 1 <= nums.length <= 10^5
* 1 <= nums[i] <= nums.length
* 0 <= k <= nums.length
*
*
*/
// @lc code=start
import java.util.ArrayList;
import java.util.List;
class Solution {
public int longestEqualSubarray(List<Integer> nums, int k) {
int n = nums.size();
// due to 1 <= nums[i] <= nums.length, so we can use the size of nums as the
// size of positionLists
List<List<Integer>> positionLists = new ArrayList<>(n + 1);
for (int i = 0; i <= n; i++)
positionLists.add(new ArrayList<>());
for (int i = 0; i < n; i++) {
List<Integer> indexs = positionLists.get(nums.get(i));
indexs.add(i - indexs.size());
}
int count = 0;
for (List<Integer> indexs : positionLists) {
if (indexs.size() <= count)
continue;
int left = 0;
for (int right = 0; right < indexs.size(); right++) {
while (indexs.get(right) - indexs.get(left) > k)
left++;
count = Math.max(count, right - left + 1);
}
}
return count;
}
}
// @lc code=end