leetcode 350. Intersection of Two Arrays II

350. Intersection of Two Arrays II

 My Submissions
Total Accepted: 4482 Total Submissions: 10704 Difficulty: Easy

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.
解析:
這個題目太刁,幾次都沒ac
先上錯誤code:
	    public int[] intersect(int[] nums1, int[] nums2) {
	        HashSet<Integer>set = new HashSet<Integer>();
	        int i,j,index = 0;
	        for(i = 0;i < Math.min(nums2.length,nums1.length); ++i) {
	           for(j = 0;j < Math.max(nums2.length,nums1.length);++j)
	                if((nums1.length > nums2.length ? (nums1[j]==nums2[i]):(nums1[i]==nums2[j]))) {
	                    set.add(nums2[i]);
	                    break;
	                }
	                ++j;
	        }
	        int[] res = new int[set.size()];
	        Iterator<Integer> iterator = set.iterator();
	        int l = 0;
	        while(iterator.hasNext()){
	            res[l++] = iterator.next();
	        }
	        return res;
	   }
不通過的樣例:
Input:[1,2,2,1][2,2]
Output:[2]
Expected:[2,2]

解答一:
Python:
class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        if len(nums1) > len(nums2):   //這裏應該是爲了更快的優化,時間複雜度主要在這裏//
            nums1, nums2 = nums2, nums1
        c = collections.Counter(nums1)
        ans = []
        for x in nums2:
            if c[x] > 0:
                ans += x,
                c[x] -= 1
        return ans

解答二:排序(Sort)+雙指針(Two Pointers)
python:
class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1, nums2 = sorted(nums1), sorted(nums2)
        p1 = p2 = 0
        ans = []
        while p1 < len(nums1) and p2 < len(nums2):
            if nums1[p1] < nums2[p2]:
                p1 += 1
            elif nums1[p1] > nums2[p2]:
                p2 += 1
            else:
                ans += nums1[p1],
                p1 += 1
                p2 += 1
        return ans



發佈了39 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章