[easy+][Array][Two-pointers]350. Intersection of Two Arrays II

原題是:

Given two arrays, write a function to compute their intersection.

***: 349.是該題的簡(jiǎn)單版本,區(qū)別是結(jié)果不需要返回重復(fù)的結(jié)果。
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.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

思路:

這個(gè)題有兩個(gè)標(biāo)準(zhǔn)解法:
1.是我代碼所寫(xiě)的two pointer方法。先將兩個(gè)數(shù)組排序,然后兩指針?lè)謩e比較對(duì)應(yīng)位置。誰(shuí)大了,挪動(dòng)另一個(gè)指針。相等則把該元素插入結(jié)果中。
2.用hash table 存第一個(gè)數(shù)組的元素對(duì)應(yīng)元素出現(xiàn)的個(gè)數(shù)。再遍歷第二個(gè)數(shù)組,對(duì)于hashtable中已有的Key,填入結(jié)果,并將value值減去1。

對(duì)follow-up:
3.如果內(nèi)存不夠,那只能用哈希的方法,第二個(gè)數(shù)組分批載入。而第一個(gè)方法,由于需要排序,無(wú)法分批載入數(shù)組。

代碼是:

class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        i,j = 0,0
        num1 = sorted(nums1)
        num2 = sorted(nums2)
        res = []
        
        while i < len(num1) and j < len(num2):
            if num1[i] < num2[j]:
                i += 1
            elif num1[i] > num2[j]:
                j += 1
            else:
                res.append(num1[i])
                i += 1
                j += 1
        return res
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 感恩冥想 1、感恩哥哥早晨起來(lái)幫助我給叔叔阿姨送早餐,讓我有足夠的時(shí)間去洗頭發(fā)整理我的衣物參加辟谷 2、感恩冠晴姐...
    欒宜閱讀 300評(píng)論 0 0
  • 今天下了很大的雨,雖然不及小時(shí)候某年夏天的暴雨。和昨天一樣,大早上掙扎著起床,為了半天50塊錢(qián)的工資。心中有一瞬間...
    青五閱讀 288評(píng)論 0 0
  • 無(wú)論是權(quán)威的PGC的時(shí)代, 還是大眾熱的UGC的當(dāng)下。 都存在的實(shí)事就是創(chuàng)造優(yōu)質(zhì)到極致! 知識(shí)變現(xiàn)的年代:追求的是...
    廬陵居士趙氏兄閱讀 125評(píng)論 0 0

友情鏈接更多精彩內(nèi)容