zoukankan      html  css  js  c++  java
  • G面经prepare: set difference

    给你A{1,2,3,4,4,5}, B{2,4},求A-B={1,3,4,5},很简单. visit 1

    只用一个HashMap

     1 package TwoSets;
     2 import java.util.*;
     3 
     4 public class Solution {
     5     public ArrayList<Integer> findDiff(int[] arr1, int[] arr2) {
     6         ArrayList<Integer> res = new ArrayList<Integer>();
     7         HashMap<Integer, Integer> m1 = new HashMap<Integer, Integer>();
     8         for (int item1 : arr1) {
     9             if (!m1.containsKey(item1)) {
    10                 m1.put(item1, 1);
    11             }
    12             else {
    13                 m1.put(item1, m1.get(item1)+1);
    14             }
    15         }
    16         for (int item2 : arr2) {
    17             if (m1.containsKey(item2)) {
    18                 m1.put(item2, m1.get(item2)-1);
    19             }
    20             if (m1.get(item2) == 0) m1.remove(item2);
    21         }
    22         for (int elem : m1.keySet()) {
    23             int num = m1.get(elem);
    24             while (num > 0) {
    25                 res.add(elem);
    26                 num--;
    27             }
    28         }
    29         return res;
    30     }
    31     
    32 
    33     /**
    34      * @param args
    35      */
    36     public static void main(String[] args) {
    37         // TODO Auto-generated method stub
    38         Solution sol = new Solution();
    39         ArrayList<Integer> res = sol.findDiff(new int[]{1,2,3,4,4,5}, new int[]{2,4});
    40         System.out.println(res);
    41     }
    42 
    43 }
  • 相关阅读:
    window.onresize绑定事件以及解绑事件
    jqGrid中select带可编辑的
    ROS(机器视觉)
    Python(time模块)
    Python(random模块)
    Python迭代器
    Python生成器
    Python装饰器(函数)
    ROS(URDF机器人建模)
    ROS基础
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5132751.html
Copyright © 2011-2022 走看看