leetcode-349. Intersection of Two Arrays

来源:互联网 发布:冒险岛数据库中心 编辑:程序博客网 时间:2024/06/16 00:00

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.

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        Map<Integer,Integer> nums1Map = new HashMap<Integer,Integer>();List<Integer> ans = new ArrayList<Integer>();for(int i = 0 ; i < nums1.length; i ++){if( null == nums1Map.get(nums1[i])) nums1Map.put(nums1[i],1);}for(int i = 0 ; i < nums2.length; i ++){if( null != nums1Map.get(nums2[i])) {ans.add(nums2[i]); nums1Map.remove(nums2[i]);}}int[] return_array = new int[ans.size()];for(int i = 0 ; i < ans.size(); i ++){    return_array[i] = ans.get(i);}return return_array;    }}

总结:简单用了hashmap做了一下,最后多了一次赋值,感觉不够优雅。

0 0