阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述: 给你两个长度为 n、下标从 0 开始的整数数组 A 和 B。 定义前缀公共数组 C 为:C[i] 等于数组 A 和 B 中下标从 0 到 i 的部分中公共元素的个数。 返回前缀公共数组 C。
示例:
输入:A = [1,3,2,4], B = [3,1,2,4] 输出:[0,2,3,4]
A 和 B 的前 i 项中各出现一次。i。A[i] 和 B[i] 加入统计。+1。package lc2657;
import java.util.HashMap;
class Solution {
public int[] findThePrefixCommonArray(int[] A, int[] B) {
int n = A.length;
int count = 0;
int[] res = new int[n];
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.computeIfAbsent(A[i], k -> 0);
map.put(A[i], map.get(A[i]) + 1);
if (map.get(A[i]) == 2) {
map.put(A[i], 0);
count++;
}
map.computeIfAbsent(B[i], k -> 0);
map.put(B[i], map.get(B[i]) + 1);
if (map.get(B[i]) == 2) {
map.put(B[i], 0);
count++;
}
res[i] = count;
}
return res;
}
}减少if分支判断,用数组替代哈希表更快更简洁:
class Solution {
public int[] findThePrefixCommonArray(int[] A, int[] B) {
int n = A.length;
int[] res = new int[n];
int[] count = new int[n + 1];
int common = 0;
for (int i = 0; i < n; i++) {
if (++count[A[i]] == 2) common++;
if (++count[B[i]] == 2) common++;
res[i] = common;
}
return res;
}
}