• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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

posted @ 2016-01-20 11:52  neverlandly  阅读(310)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3