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

xxxqqq

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.

 

Example

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

利用较小的数组建set 节省空间

 1 public class Solution {
 2     /**
 3      * @param nums1 an integer array
 4      * @param nums2 an integer array
 5      * @return an integer array
 6      */
 7     public int[] intersection(int[] nums1, int[] nums2) {
 8         // Write your code here
 9         if(nums1==null||nums2==null) return null;
10         if(nums1.length==0||nums2.length==0) return new int[0];
11         
12         Set<Integer> set = new HashSet<Integer>();
13         List<Integer> res = new ArrayList<Integer>();
14         
15         int[] num1 = nums1.length>nums2.length?nums2: nums1;
16         int[] num2 = nums1.length<nums2.length?nums2: nums1;
17         
18         for(int i: num1){
19             set.add(i);
20         }
21         
22         for(int i: num2){
23             if(set.contains(i)){
24                 res.add(i);
25                 set.remove(i);
26             }
27             if(set.size()==0) break;
28         }
29         int[] resInt = new int[res.size()];
30         int index =0;
31         for(Integer i : res){
32             resInt[index++]=i;
33         }
34         return resInt;
35     }
36 }

 

posted on 2017-05-10 15:17  xxxqqq  阅读(276)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3