G面经prepare: Set Intersection && Set Difference

 求两个sorted数组的intersection e.g. [1,2,3,4,5],[2,4,6] 结果是[2,4]
difference

类似merge, 分小于等于大于三种情况,然后时间O(m+n), 空间O(1)

 1 package ShortestSubsequenceIncluding;
 2 import java.util.*;
 3 
 4 public class Solution2 {
 5     public ArrayList<Integer> setInters(int[] arr1, int[] arr2) {
 6         int i1=0, i2=0;
 7         ArrayList<Integer> res = new ArrayList<Integer>();
 8         while (i1<arr1.length && i2<arr2.length) {
 9             if (arr1[i1] < arr2[i2]) i1++;
10             else if (arr1[i1] > arr2[i2]) i2++;
11             else {
12                 res.add(arr1[i1]);
13                 i1++;
14                 i2++;
15             }
16         }
17         return res;
18     }
19     
20     public ArrayList<Integer> setDiff(int[] arr1, int[] arr2) {
21         int i1=0, i2=0;
22         ArrayList<Integer> res = new ArrayList<Integer>();
23         while (i1<arr1.length && i2<arr2.length) {
24             if (arr1[i1] < arr2[i2]) {
25                 res.add(arr1[i1]);
26                 i1++;
27             }
28             else if (arr1[i1] > arr2[i2]) {
29                 i2++;
30             }
31             else {
32                 i1++;
33                 i2++;
34             }
35         }
36         while (i1 < arr1.length) {
37             res.add(arr1[i1]);
38             i1++;
39         }
40         return res;
41     }
42     
43 
44     /**
45      * @param args
46      */
47     public static void main(String[] args) {
48         // TODO Auto-generated method stub
49         Solution2 sol = new Solution2();
50         ArrayList<Integer> res1 = sol.setInters(new int[]{1,2,3,4,4,5}, new int[]{2,4,4,6});
51         ArrayList<Integer> res2 = sol.setDiff(new int[]{2,3,4,4,4,5}, new int[]{1,2,4,4,6});
52         System.out.println(res2);
53 
54     }
55 
56 }

如果是无序的两个array,则Build两个hashMap, 遍历第一个map的keySet, O(m+n)time, O(m+n)space

你可能感兴趣的:(G面经prepare: Set Intersection && Set Difference)