资源引用:
今日小记:
平台提交系统出现故障,正在维修中~。
稀土掘金-367.好子数组的计数(367.好子数组的计数)
题目分析:
给定一个正整数数组nums,给定一个正整数k,求nums中有多少个连续的子数组中恰好包含k个不同的整数,即“好子数组”的数量。
解题重点:
用哈希表记录增广窗口确定的连续子数组中的不同整数,哈希表的长度即为连续子数组所包含的不同整数的个数。此题与148.小A的子数组权值有相似之处,详细思路不再赘述。
import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
public class Main {
public static int solution(int[] nums, int k) {
int res = 0;
for (int left = 0 ; left < nums.length; left++) {
Set<Integer> set = new HashSet<>();
for (int right = left; right < nums.length; right++) {
set.add(nums[right]);
if (set.size() == k) res++;
}
}
return res;
}
public static void main(String[] args) {
System.out.println(solution(new int[]{1, 2, 1, 2, 3}, 2) == 7 ? 1 : 0);
System.out.println(solution(new int[]{1, 2, 1, 3, 2}, 3) == 5 ? 1 : 0);
System.out.println(solution(new int[]{1, 1, 1, 1}, 1) == 10 ? 1 : 0);
}
}
稀土掘金-291.禁着点方案数(291.禁着点方案数)
题目分析:
给定一个被称为“禁着点数组”的长度为n的整型数组a,以及一个目标和s,求有多少对正整数(x, y)满足x + y = s且x和y都不在禁着点的数组中。注意:(x,y)和(y,x)视为两个不同的正整数对。
解题重点:
对于任意一个小于s的正整数x,都能找到与之组队的y,使得x + y = s。
对于给定的数组a,用哈希表统计其包含的整数种类,以便在后续查询禁着点的过程中省去重复遍历。
解题思路:
- 遍历数组a,构建其哈希表
- 遍历小于等于 s/2 的正整数x,查询x和y=s-x是否存在于哈希表中,若x和y均不存在于哈希表中,则除x = y之外,方案数res += 2,x = y时方案数res++。
- 最终返回res。
import java.util.Set;
import java.util.HashSet;
public class Main {
public static int solution(int n, int[] a, int s) {
int res = 0;
Set<Integer> set = new HashSet<>();
/*1.遍历数组a,构建其哈希表 */
for (int num : a) {
set.add(num);
}
/*2. */
for (int x = 1; x <= (s / 2); x++) {
int y = s - x;
if (!set.contains(x) && !set.contains(y)) {
if (x == y) res++;
else res += 2;
}
}
return res;
}
public static void main(String[] args) {
System.out.println(solution(3, new int[]{1, 2, 3}, 10) == 3);
System.out.println(solution(2, new int[]{5, 9}, 15) == 10);
System.out.println(solution(4, new int[]{1, 6, 9, 4}, 13) == 6);
}
}