zoukankan      html  css  js  c++  java
  • 349. Intersection of Two Arrays【双指针|二分】

    2017/3/23 15:41:47

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

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

    Note:

    • Each element in the result must be unique.
    • The result can be in any order.

     
    作弊版:Python
    class Solution(object):
        def intersection(self, nums1, nums2):
            return list(set( nums1 ) & set(nums2))
     
    版本1:Java  O(m*n)  循环检查  
    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            Set<Integer> set = new HashSet<Integer>();
            for ( int i=0;i<nums1.length;i++ )
                for ( int j=0;j<nums2.length;j++ )
                    if ( nums1[i] == nums2[j] ){
                        set.add(nums1[i]);
                        break;
                    }
            Object[] obj = set.toArray();
            int[] rs = new int[obj.length];
            for ( int i=0;i<obj.length;i++ )
            	rs[i] = (int)obj[i];
            return rs;
        }
    }
     
    版本2:Java  O(m+n)  借助哈希表+Set,或者双Set
    public int[] intersection(int[] nums1, int[] nums2) {
    		Map<Integer,Boolean> map = new Hashtable<Integer,Boolean>();
    		Set<Integer> set = new TreeSet<Integer>();
            for ( int i=0;i<nums1.length;i++ )
                map.put( nums1[i] , true );
            for ( int j=0;j<nums2.length;j++ ){
            	if (map.get(nums2[j]) == null ) continue;
            	set.add(nums2[j]);
            }
            int i = 0;
            int[] rs = new int[set.size()];
            for ( Integer num : set )
            	rs[i++] = num;
            return rs;
        }
    

      

     
     
  • 相关阅读:
    Helpers Overview
    Validation
    Support Facades
    Session Store
    位运算(参考百科)
    开源项目_可能使用到的开源项目集合
    秒杀系统架构分析与实战(转)
    shell命令之根据字符串查询文件对应行记录
    MySQL做为手动开启事务用法
    spring 加载bean过程源码简易解剖(转载)
  • 原文地址:https://www.cnblogs.com/flyfatty/p/6624806.html
Copyright © 2011-2022 走看看