1. 程式人生 > >LeetCode oj 349. Intersection of Two Arrays(HashSet)

LeetCode oj 349. Intersection of Two Arrays(HashSet)

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.
給你兩個陣列,求兩個陣列中重複的元素 一直在用C++寫ACM題,對java類庫不是很熟悉,知道應該用set寫,但是不會用hashset。。。。於是純暴力寫了一個,不過時間複雜度還好,A了之後學了一下set用法,一起放到這裡 暴力解法:
public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        int hash1[] = new int [65535];
        int hash2[] = new int [65535];
        for(int i=0;i<len1;i++){
            hash1[nums1[i]]++;
        }
        for(int i=0;i<len2;i++){
            hash2[nums2[i]]++;
        }
        int index = 0;
        int count = 0;
        for(int i=0;i<len1;i++){
            if(hash2[nums1[i]] == 0){
                hash1[nums1[i]] = 0;
            }
        }
        for(int i=0;i<65535;i++){
            if(hash1[i] != 0){
                count++;
            }
        }
        int re[] = new int [count];
        for(int i=0;i<65535;i++){
             if(hash1[i] != 0){
                re[index++] = i;
            }
        }
        return re;
    }
}
HashSet:
public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer>set = new HashSet<Integer>();
        int len1 = nums1.length;
        int len2 = nums2.length;
        for(int i=0;i<len1;i++){
            set.add(nums1[i]);
        }
        List<Integer>list = new ArrayList<Integer>();
        for(int i=0;i<len2;i++){
            if(set.contains(nums2[i])){
                list.add(nums2[i]);
                set.remove(nums2[i]);
            }
        }
        int size = list.size();
        int re[] = new int [size];
        for(int i=0;i<size;i++){
            re[i] = list.get(i);
        }
        return re;
    }
}