ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【leetCode周赛】【美团第 262 场周赛】:leetCode:2032. 至少在两个数组中出现的值

2021-10-16 19:03:57  阅读:134  来源: 互联网

标签:周赛 int length nums1 262 add 数组 leetCode nums2


1、题目描述

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

2、算法分析

3个数组,题目要求求出数组中的数字,这个数字至少是在其中的两个数组中出现过。求出数组中符合条件的数字。

暴力暴力!!

注意:

Set是存储不重复的元素。当重复添加的时候,还是添加一个。

public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(1);
        set.add(3);
        for (Integer a : set) {
            System.out.println(a);
        }
}

输出结果:

 最后存储的是List集合:

现在使用的是Set集合。最后返回的是List集合

/**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        Object[] a = c.toArray();
        if ((size = a.length) != 0) {
            if (c.getClass() == ArrayList.class) {
                elementData = a;
            } else {
                elementData = Arrays.copyOf(a, size, Object[].class);
            }
        } else {
            // replace with empty array.
            elementData = EMPTY_ELEMENTDATA;
        }
    }

3、代码实现

import java.util.*;
class Solution {
    public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {
        Set<Integer> res = new HashSet<>();
        
        // 遍历数组,将数组元素存储到Set集合中,存储过程中判断是否重复,并计算重复的个数
        for(int i = 0;i < nums1.length;i++){
            for(int j = 0;j < nums2.length;j++){
                if(nums1[i] == nums2[j]){
                    res.add(nums1[i]);
                }
            }
        }
       
        for(int i = 0;i < nums1.length;i++){
            for(int j = 0;j < nums3.length;j++){
                if(nums1[i] == nums3[j]){
                    res.add(nums1[i]);
                }
            }
        }
        for(int i = 0;i < nums2.length;i++){
            for(int j = 0;j < nums3.length;j++){
                if(nums2[i] == nums3[j]){
                    res.add(nums2[i]);
                }
            }
        }
       
        List<Integer> l = new ArrayList<>(res);
        
        return l;
    }
}

标签:周赛,int,length,nums1,262,add,数组,leetCode,nums2
来源: https://blog.csdn.net/Sunshineoe/article/details/120802111

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有