Java實現-兩數組的交2

計算兩個數組的交

 注意事項

每個元素出現次數得和在數組裏一樣
答案可以以任意順序給出

樣例

nums1 = [1, 2, 2, 1], nums2 = [2, 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
        if(nums1==null||nums2==null){
			return null;
		}
		HashMap<Integer, Integer> map1=new HashMap<Integer, Integer>();
		HashMap<Integer, Integer> map2=new HashMap<Integer, Integer>();
		List<Integer> result=new ArrayList<Integer>();
		for(int i=0;i<nums1.length;i++){
			if(map1.containsKey(nums1[i])){
				map1.put(nums1[i], map1.get(nums1[i])+1);
			}else{
				map1.put(nums1[i], 1);
			}
		}
		for(int i=0;i<nums2.length;i++){
			if(map2.containsKey(nums2[i])){
				map2.put(nums2[i], map2.get(nums2[i])+1);
			}else{
				map2.put(nums2[i], 1);
			}
		}
		Set<Integer> set1=map1.keySet();
		Iterator<Integer> it1=set1.iterator();
		while(it1.hasNext()){
			int temp=it1.next();
			if(map2.containsKey(temp)){
				int n=Math.min(map2.get(temp), map1.get(temp));
				for(int i=0;i<n;i++){
					result.add(temp);
				}
			}
		}
		int[] nums=new int[result.size()];
		for(int i=0;i<result.size();i++){
			nums[i]=result.get(i);
		}
		return nums;
    }
}


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