美文网首页
350. Intersection of Two Arrays

350. Intersection of Two Arrays

作者: namelessEcho | 来源:发表于2017-10-03 11:09 被阅读0次

因为这题要计算数量了所以不能用再用Set了。
我先预排序了一下,然后是这样的一个过程。使用一个while自增pos2找到nums2中比当前nums1【POS1】要大或者等于的数,判断当前的数是否相等,等的话在while循环中在移动pos1和pos2两个指针,如果不等的话,再使用while自增pos1找到nums1中比当前nums2【pos2】要大于或者等于的数。

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        ArrayList<Integer> result = new ArrayList<>();
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int len1 = nums1.length;
        int len2 = nums2.length;
        int pos1 = 0;
        int pos2 = 0;
        while(pos1<nums1.length)
        {
            while(pos2<nums2.length&&nums2[pos2]<nums1[pos1])
                pos2++;
            if(pos2==nums2.length)break;
            if(nums2[pos2]==nums1[pos1])
            {
                while(pos2<nums2.length&&nums2[pos2]==nums1[pos1])
                {
                       result.add(nums2[pos2]);
                       pos2++;
                       pos1++;
                      if(pos1==nums1.length) break;
                }
            if(pos2==nums2.length)break;
            }
            else
            {
                while(pos1<nums1.length&&nums2[pos2]>nums1[pos1])
                    pos1++;
            }
        }
         int[] array = new int[result.size()];
        for(int i = 0 ;i<array.length;i++)
        {
            array[i]=result.get(i);
        }
        return array;
    }
}

相关文章

网友评论

      本文标题:350. Intersection of Two Arrays

      本文链接:https://www.haomeiwen.com/subject/sxcxyxtx.html