leetcode 350. Intersection of Two Arrays II

来源:互联网 发布:java统计报表怎么做 编辑:程序博客网 时间:2024/05/21 17:17

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



0 0
原创粉丝点击