【LeeCode】2032. 至少在两个数组中出现的值

时间:2022-12-29 08:56:14


【题目描述】

给你三个整数数组 ​nums1​​nums2​ 和 ​nums3​ ,请你构造并返回一个 元素各不相同的 数组,且由 至少 在 两个 数组中出现的所有值组成。数组中的元素可以按 任意 顺序排列。

​https://leetcode.cn/problems/two-out-of-three/​


【示例】

【LeeCode】2032. 至少在两个数组中出现的值

【代码】admin

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* 2022-12-29
*/

class Solution {
public List<Integer> twoOutOfThree(int[] num1, int[] num2, int[] num3) {
List<Integer> list = new ArrayList<>();
Map<Integer,Integer> map = new HashMap<>();
Map<Integer,Integer> map1 = new HashMap<>();
Map<Integer,Integer> map2 = new HashMap<>();

for(int x : num1){
map.put(x, map.getOrDefault(x, 0) + 1);
}
for(int x : num2){
map1.put(x, map1.getOrDefault(x, 0) + 1);
}
for(int x : num3){
map2.put(x, map2.getOrDefault(x, 0) + 1);
}
for (int i = 0; i < num1.length; i++){
if (map1.containsKey(num1[i]) || map2.containsKey(num1[i])){
if (!list.contains(num1[i]))
list.add(num1[i]);
}
}
for (int i = 0; i < num2.length; i++){
if (map.containsKey(num2[i]) || map2.containsKey(num2[i])){
if (!list.contains(num2[i]))
list.add(num2[i]);
}
}
System.out.println(list);
return list;
}
}

public class Test {
public static void main(String[] args) {
int[] nums1 = {1,1,3,2};
int[] nums2 = {2,3};
int[] nums3 = {3};

new Solution().twoOutOfThree(nums1,nums2,nums3); // [3,2]

int[] num1 = {3,1};
int[] num2 = {2,3};
int[] num3 = {1,2};

new Solution().twoOutOfThree(num1,num2,num3); // [2,3,1]


int[] nu1 = {2,15,10,11,14,12,14,11,9,1};
int[] nu2 = {8,9,13,2,11,8};
int[] nu3 = {13,5,15,7,12,7,8,3,13,15};

new Solution().twoOutOfThree(nu1,nu2,nu3); // [8,13,2,15,11,12,9]
}
}