class Solution {
public int[] findIntersectionValues(int[] nums1, int[] nums2) {
HashSet<Integer> set1 = new HashSet<>();
for (int x : nums1) {
set1.add(x);
}
HashSet<Integer> set2 = new HashSet<>();
for (int x : nums2) {
set2.add(x);
}
int[] ans = new int[2];
for (int x : nums1) {
if (set2.contains(x)) {
ans[0]++;
}
}
for (int x : nums2) {
if (set1.contains(x)) {
ans[1]++;
}
}
return ans;
}
}
给你一个下标从 0 开始的字符串 word
。
一次操作中,你可以选择 word
中任意一个下标 i
,将 word[i]
修改成任意一个小写英文字母。
请你返回消除 word
中所有相邻 近似相等 字符的 最少 操作次数。
两个字符 a
和 b
如果满足 a == b
或者 a
和 b
在字母表中是相邻的,那么我们称它们是 近似相等 字符。
示例 1:
输入:word = "aaaaa" 输出:2 解释:我们将 word 变为 "acaca" ,该字符串没有相邻近似相等字符。 消除 word 中所有相邻近似相等字符最少需要 2 次操作。
示例 2:
输入:word = "abddez" 输出:2 解释:我们将 word 变为 "ybdoez" ,该字符串没有相邻近似相等字符。 消除 word 中所有相邻近似相等字符最少需要 2 次操作。
每次改相邻的右边那个
class Solution {
public int removeAlmostEqualCharacters(String word) {
int ans = 0;
char[] arr = word.toCharArray();
int n = arr.length;
for (int i = 1; i < n; i++) {
if (Math.abs(arr[i] - arr[i - 1]) <= 1) {
ans += 1;
i += 1;
}
}
return ans;
}
}
给你一个整数数组 nums
和一个整数 k
。
一个元素 x
在数组中的 频率 指的是它在数组中的出现次数。
如果一个数组中所有元素的频率都 小于等于 k
,那么我们称这个数组是 好 数组。
请你返回 nums
中 最长好 子数组的长度。
子数组 指的是一个数组中一段连续非空的元素序列。
示例 1:
输入:nums = [1,2,3,1,2,3,1,2], k = 2 输出:6 解释:最长好子数组是 [1,2,3,1,2,3] ,值 1 ,2 和 3 在子数组中的频率都没有超过 k = 2 。[2,3,1,2,3,1] 和 [3,1,2,3,1,2] 也是好子数组。 最长好子数组的长度为 6 。
滑动窗口
class Solution {
public int maxSubarrayLength(int[] nums, int k) {
int ans = 0;
int left = 0;
int n = nums.length;
Map<Integer, Integer> cnt = new HashMap<>();
for (int i = 0; i < n; i++) {
cnt.merge(nums[i], 1, Integer::sum);
while (cnt.get(nums[i]) > k) {
cnt.merge(nums[left++], -1, Integer::sum);
}
ans = Math.max(ans, i - left + 1);
}
return ans;
}
}