加油呀,打工人,美好的一天从打工开始!
题目描述
给你三个整数数组 nums1、nums2 和 nums3 ,请你构造并返回一个 元素各不相同的 数组,且由 至少 在 两个 数组中出现的所有值组成。数组中的元素可以按 任意 顺序排列。
示例 1:
输入:nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]
输出:[3,2]
解释:至少在两个数组中出现的所有值为:
- 3 ,在全部三个数组中都出现过。
- 2 ,在数组 nums1 和 nums2 中出现过。
示例 2:
输入:nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]
输出:[2,3,1]
解释:至少在两个数组中出现的所有值为:
- 2 ,在数组 nums2 和 nums3 中出现过。
- 3 ,在数组 nums1 和 nums2 中出现过。
- 1 ,在数组 nums1 和 nums3 中出现过。
示例 3:
输入:nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]
输出:[]
解释:不存在至少在两个数组中出现的值。
提示:
1 <= nums1.length, nums2.length, nums3.length <= 100
1 <= nums1[i], nums2[j], nums3[k] <= 100
求解思路
- 这道题目就是通过题目给定的要求进行模拟即可。
- 参考其他人的题解,也可以通过哈希表和位运算来求解。
实现代码
class Solution {
List<Integer> res=new ArrayList<>();
public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {
for(int i=0;i<nums1.length;i++){
if(isExist(nums1[i],nums2)&&isExist(nums1[i],nums3)||isExist(nums1[i],nums3)||isExist(nums1[i],nums2)){
if(!res.contains(nums1[i])){
res.add(nums1[i]);
}
}
}
for(int i=0;i<nums2.length;i++){
if(isExist(nums2[i],nums3)){
if(!res.contains(nums2[i])){
res.add(nums2[i]);
}
}
}
return res;
}
public boolean isExist(int num,int[] nums){
for(int v:nums){
if(v==num) return true;
}
return false;
}
}
运行结果

本文介绍了一个有趣的编程问题:如何找出三个数组中至少出现在两个数组中的所有不同元素,并提供了一种解决方案。通过遍历每个数组检查元素是否存在其他数组中,确保最终结果只包含独特元素。


被折叠的 条评论
为什么被折叠?



