Advertisement
sweet1cris

Untitled

Sep 21st, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.56 KB | None | 0 0
  1. // Assumptions: there could be duplicated elements in the given arrays.
  2. public class CommonNumbersII {
  3.   // Method 1: two pointers.
  4.   public List<Integer> commonI(int[] a, int[] b) {
  5.     // Assumption: a, b is not null.
  6.     List<Integer> common = new ArrayList<Integer>();
  7.     int i = 0;
  8.     int j = 0;
  9.     while (i < a.length && j < b.length) {
  10.       if (a[i] == b[j]) {
  11.         common.add(a[i]);
  12.         i++;
  13.         j++;
  14.       } else if (a[i] < b[j]) {
  15.         i++;
  16.       } else {
  17.         j++;
  18.       }
  19.     }
  20.     return common;
  21.   }
  22.  
  23.   // Method 2: use HashMap.
  24.   public List<Integer> commonII(int[] a, int[] b) {
  25.     List<Integer> common = new ArrayList<Integer>();
  26.     HashMap<Integer, Integer> countA = new HashMap<Integer, Integer>();
  27.     for (int num : a) {
  28.       Integer ct = countA.get(num);
  29.       if (ct != null) {
  30.         countA.put(num, ct + 1);
  31.       } else {
  32.         countA.put(num, 1);
  33.       }
  34.     }
  35.     HashMap<Integer, Integer> countB = new HashMap<Integer, Integer>();
  36.     for (int num : b) {
  37.       Integer ct = countB.get(num);
  38.       if (ct != null) {
  39.         countB.put(num, ct + 1);
  40.       } else {
  41.         countB.put(num, 1);
  42.       }
  43.     }
  44.     for (Map.Entry<Integer, Integer> entry : countA.entrySet()) {
  45.       Integer ctInB = countB.get(entry.getKey());
  46.       if (ctInB != null) {
  47.         int appear = Math.min(entry.getValue(), ctInB);
  48.         for (int i = 0; i < appear; i++) {
  49.           common.add(entry.getKey());
  50.         }
  51.       }
  52.     }
  53.     return common;
  54.   }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement