zoukankan      html  css  js  c++  java
  • 350. Intersection of Two Arrays II java solutions

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

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

    Note:

    • Each element in the result should appear as many times as it shows in both arrays.
    • The result can be in any order.

    Follow up:

    • What if the given array is already sorted? How would you optimize your algorithm?
    • What if nums1's size is small compared to nums2's size? Which algorithm is better?
    • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

    Subscribe to see which companies asked this question

     1 public class Solution {
     2     public int[] intersect(int[] nums1, int[] nums2) {
     3         Set<Integer> set = new HashSet<Integer>();
     4         Arrays.sort(nums1);
     5         Arrays.sort(nums2);
     6         for(int i = 0,j = 0; i < nums1.length && j < nums2.length;){
     7             if(nums1[i] == nums2[j]){
     8                 set.add(i++);
     9                 j++;
    10             }else if(nums1[i] < nums2[j]) i++;
    11             else j++;
    12         }
    13         
    14         int[] ans = new int[set.size()];
    15         int k = 0;
    16         for(Integer n : set){
    17             ans[k++] = nums1[n];
    18         }
    19         return ans;
    20     }
    21 }

    使用hashset 记录重复出现元素的下标。

  • 相关阅读:
    P1247 取火柴游戏 (奇异局势)
    1290A
    P1236 算24点
    LCP 4. 覆盖
    leetcode 1066. 校园自行车分配 II
    hdu 2255 奔小康赚大钱
    NC200546 回文串
    上市是什么意思 为什么上市就有钱了
    主板、中小板、创业板、新三板的区别是什么?
    熔断机制
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5653912.html
Copyright © 2011-2022 走看看