• 【力扣】两个数组的交集 II


    给定两个数组,编写一个函数来计算它们的交集。

    示例 1:

    输入:nums1 = [1,2,2,1], nums2 = [2,2]
    输出:[2,2]
    示例 2:

    输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
    输出:[4,9]
     

    说明:

    输出结果中每个元素出现的次数,应与元素在两个数组中出现次数的最小值一致。
    我们可以不考虑输出结果的顺序。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii

    这个问题真是搞不懂我了,我以为是连续的,没想到随便都可以,以后要注意读题啊。

    解题方法1:使用hashMap的方式

    public int[] intersect(int[] nums1, int[] nums2) {
            if (nums1.length < nums2.length){
                return intersect(nums2,nums1);
            }
            Map<Integer,Integer> map = new HashMap<>();
            //得到数据较多的那个数组的key / value
            for (int i =0 ;i< nums1.length;i++){
                int temp =nums1[i];
                if (map.containsKey(temp)){
                    map.put(temp,map.get(temp) + 1);
                } else {
                    map.put(temp,1);
                }
            }
            int result[] = new int[nums2.length];
            int index = 0;
            //循环数组,如果这个数组中有对应数据,则把有的数据放入到result中.
            for (int i = 0;i< nums2.length; i++){
                Integer value = map.get(nums2[i]);
                if ( value != null && value > 0){
                    map.put(nums2[i],value-1);
                    result[index++] = nums2[i];
                }
            }
            return Arrays.copyOfRange(result,0,index);
        }

    解答二:

    public int[] intersect(int[] nums1, int[] nums2) {
    
            //直接排序,升序
            Arrays.sort(nums1);
            Arrays.sort(nums2);
    
            int index1 = 0 , index2 = 0 , index = 0;
            int indexLength1 = nums1.length , indexLength2 = nums2.length;
            int result[] = new int[indexLength1 > indexLength2 ? indexLength2 : indexLength1];
            
            //通过循环的方式,把result处理了
            while(index1 < indexLength1 && index2 < indexLength2){
                if (nums1[index1] < nums2[index2]){
                    index1++;
                } else if (nums1[index1] > nums2[index2]){
                    index2++;
                }else {
                    result[index] = nums1[index1];
                    index++;
                    index1++;
                    index2++;
                }
            }
            //注意这里包括下标from,不包括上标to
            return Arrays.copyOfRange(result,0,index);
        } 
    一个入行不久的Java开发,越学习越感觉知识太多,自身了解太少,只能不断追寻
  • 相关阅读:
    应急响应中find命令总结
    应急响应排查思路
    硬链接与软链接的区别
    Linux开机启动项总结
    android 開發常用網站
    epoll
    Qualcomm platform, the commonly used parameters of charger and battery in device tree file
    why not ovp protection ?
    Performance tuning
    Using adb over wifi
  • 原文地址:https://www.cnblogs.com/fengtingxin/p/13296538.html
Copyright © 2020-2023  润新知