码迷,mamicode.com
首页 > 其他好文 > 详细

G面经prepare: set difference

时间:2016-01-15 12:52:21      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

 

给你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 }

 

G面经prepare: set difference

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5132751.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!