leetcode-350.兩個數組的交集 II

題目

給定兩個數組,寫一個方法來計算它們的交集。

例如:
給定 nums1 = [1, 2, 2, 1]nums2 = [2, 2], 返回 [2, 2].

注意:

  •    輸出結果中每個元素出現的次數,應與元素在兩個數組中出現的次數一致。
  •    我們可以不考慮輸出結果的順序。

跟進:

  • 如果給定的數組已經排好序呢?你將如何優化你的算法?
  • 如果 nums1 的大小比 nums2 小很多,哪種方法更優?

  • 如果nums2的元素存儲在磁盤上,內存是有限的,你不能一次加載所有的元素到內存中,你該怎麼辦?

解法1

哈希表

分析過程

1)創建哈希表,遍歷數組1,將數值作爲哈希表的鍵,數值出現的次數作爲值,存儲在哈希表中

2)遍歷數組2,如果該項值與哈希表中鍵相等,存儲該值,並將該值出現的次數減1

代碼實現

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int len1=nums1.length;
        int len2=nums2.length;
        if(len1==0 || len2==0){
            return new int[0];
        }
        Map<Integer,Integer> map=new HashMap<Integer,Integer>();
        for(int i=0;i<len1;i++){
            Integer value=map.get(nums1[i]);
            //存儲當前數值的個數
            map.put(nums1[i],(value==null?1:value+1));
        }
        List<Integer> list=new ArrayList<Integer>();
        for(int i=0;i<len2;i++){
            if(map.containsKey(nums2[i]) && map.get(nums2[i])!=0){
                list.add(nums2[i]);   
                //修改當前數值的個數
                map.put(nums2[i],map.get(nums2[i])-1);
            }
        }
        int[] results=new int[list.size()];
        int i=0;
        for(Integer tmp:list){
            results[i++]=tmp;
        }
        return results;
    }
    
}

解法2

排序

分析過程

1)將數組1,數組2分別排序

2)遍歷數組1,數組2,如果值相等,存儲該值,如果數組1值小於數組2的值,數組1下標加1,否則數組2的下標加1

代碼實現

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int len1=nums1.length;
        int len2=nums2.length;
        if(len1==0 || len2==0){
            return new int[0];
        }
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i=0;
        int j=0;
        List<Integer> list=new ArrayList();        
        while(i<len1 && j<len2){
            if(nums1[i]==nums2[j]){
                list.add(nums1[i]);
                i++;
                j++;
            }else if(nums1[i]<nums2[j]){
                i++;
            }else{
                j++;
            }
        }        
        int k=0;
        int[] result=new int[list.size()];
        for(Integer tmp:list){
            result[k++]=tmp;
        }
        return result;        
    }
    
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章