IntersectionOfTwoArraysOPT [source code]


public class IntersectionOfTwoArraysOPT {
    public int[] intersection(int[] nums1, int[] nums2) {
        boolean[] exist = new boolean[10000];
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < nums1.length; i++) {
            exist[nums1[i]] = true;
        }
        for (int i = 0; i < nums2.length; i++) {
            if (exist[nums2[i]]) {
                list.add(nums2[i]);
                exist[nums2[i]] = false;
            }
        }
        int[] result = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            result[i] = list.get(i);
        }
        return result;
    }
}

这个是 submission 最优解, 2ms, 99%;

这个算法核心其实还是一个暴力搜. 不同的是他没有依赖set, 而是用 array 来实现; 实现的过程中稍微使用了一下value as index的技巧;

所谓的value as index, 其实就有点类似于看算法书的时候学习的reverse dictionary的思路; 我们反正给 nums2来检索的时候肯定是index by value of nums1的, 所以建立一个dictionary indexed by nums1[i]实际上也是合情合理的; 不过我们实际实现的时候不用hashtbale, 而是用 array; 因为这里要完成的目的很简单, 就是一个单纯的existence check or counter; 这种是typical situation where hash table can be replaced by an array;

另外注意他最后 return 的时候, list to array其实也是手工做的, 虽然他这个手工 conversion 没有我的做的那么 elegant;

discussion 里面提到了其他的思路:

  1. 两个 array 分别 sort 之后用用2pointers 来做; 这个其实可以尝试, 但是并不优越;
  2. 用binary search来做; 这个好像看哪个面经的时候碰到过, 适合在非常大的 scale 的时候用; 具体代码不贴了;

Problem Description

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.
Difficulty:Easy
Category:Algorithms
Acceptance:46.97%
Contributor: LeetCode
Companines
Two Sigma
Related Topics
binary search hash table two pointers sort
Similar question
Intersection of Two Arrays II

results matching ""

    No results matching ""