两数组的交 II

来源:互联网 发布:windows syswow64权限 编辑:程序博客网 时间:2024/04/29 22:00
样例

nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].


public class Lint548 {
    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        // Write your code here
       /* Arrays.sort(nums1);
        Arrays.sort(nums2);
        ArrayList<Integer> result = new ArrayList<Integer>();
        int i =0,j=0;
        while(i<nums1.length && j<nums2.length){
        if(nums1[i]==nums2[j]){
        result.add(nums1[i]);
        i++;
        j++;
        }
        else if(nums1[i]< nums2[j]){
        i++;
        }
        else
        {
        j++;
        }
        }
        int[] res = new int[result.size()];
        for(int k =0;k<result.size();k++){
        res[k] = result.get(k);
        }
        return res;*/
    //使用HashMap的方法 先把nums1添加到Map中,再与nums2比较
    HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
    for(int i=0;i<nums1.length;i++){
    if(!map.containsKey(nums1[i])){
    map.put(nums1[i], 1);
    }
    else{
    map.put(nums1[i], map.get(nums1[i])+1);
    }
    }
    ArrayList<Integer> result = new ArrayList<Integer>();
    for(int j = 0;j<nums2.length;j++){
    if(map.containsKey(nums2[j])){
    result.add(nums2[j]);
    map.put(nums2[j],map.get(nums2[j])-1);
    if(map.get(nums2[j])==0)//已经不存在就去掉
    map.remove(nums2[j]);
    }
    }
    int[] res=new int[result.size()];
    for(int k =0;k<result.size();k++)
    res[k]=result.get(k);
    return res;


    }
    
    public static void main(String[] args) {
       int[] nums1={1,2,2,1};
       int[] nums2={2,2};
       Lint548 test = new Lint548();
       int[] A =  test.intersection(nums1, nums2);
       for(int i = 0;i<A.length;i++)
      System.out.print(A[i]+"  " );
    }
}


样例

nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2].

public class Solution {
    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        // Write your code here
       HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
    for(int i=0;i<nums1.length;i++){
    if(!map.containsKey(nums1[i])){
    map.put(nums1[i], 1);
    }
    }
    ArrayList<Integer> result = new ArrayList<Integer>();
    for(int j = 0;j<nums2.length;j++){
    if(map.containsKey(nums2[j])){
    result.add(nums2[j]);
    map.remove(nums2[j]);
    }
    }
    int[] res=new int[result.size()];
    for(int k =0;k<result.size();k++)
    res[k]=result.get(k);
    return res;
    }
}

0 0
原创粉丝点击