• leetcode| Intersection of Two Arrays II


    Given two arrays, write a function to compute their intersection.

    Example:
    Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

    题目:升级版找两个数组的交集,初级版只对交集元素有要求,这个升级版还对元素的数量有要求

    思路:偷懒一下,用Intersection of Two Arrays 的算法改动一下,看了下讨论,基本也是用hash,欢迎交流不同解法

    public int[] intersect(int[] nums1, int[] nums2) {
      int len1 = nums1.length;
      int len2 = nums2.length;

      if(len1==0 || len2==0){
        return new int[0];
      }

      HashMap<Integer,Integer> map1 = new HashMap<Integer,Integer>();
      HashMap<Integer,Integer> map2 = new HashMap<Integer,Integer>();

      for(int i = 0;i<len1;i++){
        Integer temp = map1.get(nums1[i]);
        if(temp == null){
          map1.put(nums1[i],1);
        }else{
          map1.put(nums1[i],temp+1);
        }
      }

       for(int i = 0;i<len2;i++){
        Integer temp = map2.get(nums2[i]);
        if(temp == null){
          map2.put(nums2[i],1);
        }else{
          map2.put(nums2[i],temp+1);
        }
      }

      boolean flag = map1.size()>map2.size();
      if(!flag){
        HashMap<Integer,Integer> tempMap = map1;
        map1 = map2;
        map2 = tempMap;
      }
      List<Integer> resList = new ArrayList<Integer>();
      for(Entry e : map1.entrySet()){
        Integer key = (Integer)e.getKey();
        Integer v1 = (Integer)e.getValue();
        if(map2.get(key)!=null){
        Integer v2 = map2.get(key);
        int n = v1>v2?v2:v1;
        for(int i = 0;i<n;i++){
          resList.add(key);
          }
        }
      }
      int resSize = resList.size();
      int res [] = new int[resSize];
      for(int i = 0;i<resSize;i++){
        res[i] = resList.get(i);
      }
      return res;
    }

    StayHungry 求知若渴 StayFoolish 放低姿态
  • 相关阅读:
    Codeforces 903F Clear the Matrix
    Codeforces 899D Shovel Sale
    Codeforces 898E Squares and not squares
    Codeforces 899B Months and Years
    Codeforces 854B Maxim Buys an Apartment:贪心
    BZOJ 1198 [HNOI2006]军机调度:dfs
    BZOJ 1196 [HNOI2006]公路修建问题:二分 + 贪心生成树check(类似kruskal)
    BZOJ 1193 [HNOI2006]马步距离:大范围贪心 小范围暴搜
    BZOJ 1192 [HNOI2006]鬼谷子的钱袋:二进制 砝码称重问题
    BZOJ 1191 [HNOI2006]超级英雄Hero:二分图匹配 匈牙利算法
  • 原文地址:https://www.cnblogs.com/wujunjie/p/5688010.html
Copyright © 2020-2023  润新知