1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        ?LeetCode刷題實(shí)戰(zhàn)442:數(shù)組中重復(fù)的數(shù)據(jù)

        共 1259字,需瀏覽 3分鐘

         ·

        2021-11-19 05:34

        算法的重要性,我就不多說(shuō)了吧,想去大廠,就必須要經(jīng)過(guò)基礎(chǔ)知識(shí)和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號(hào)后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !

        今天和大家聊的問(wèn)題叫做?數(shù)組中重復(fù)的數(shù)據(jù),我們先來(lái)看題面:
        https://leetcode-cn.com/problems/find-all-duplicates-in-an-array/

        Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.


        You must write an algorithm that runs in O(n) time and uses only constant extra space.

        給定一個(gè)整數(shù)數(shù)組 a,其中1 ≤ a[i] ≤ n (n為數(shù)組長(zhǎng)度), 其中有些元素出現(xiàn)兩次而其他元素出現(xiàn)一次。
        找到所有出現(xiàn)兩次的元素。
        你可以不用到任何額外空間并在O(n)時(shí)間復(fù)雜度內(nèi)解決這個(gè)問(wèn)題嗎?

        示例


        輸入:
        [4,3,2,7,8,2,3,1]

        輸出:
        [2,3]


        解題

        哈希法:以原數(shù)組的下標(biāo)作為哈希值,遇到出現(xiàn)一次的數(shù),在這個(gè)數(shù)所指向的下標(biāo)處數(shù)值變?yōu)樨?fù)數(shù),遇到出現(xiàn)第二次的數(shù)時(shí),以它為下標(biāo)指向的數(shù)是負(fù)數(shù),以此判斷。

        class?Solution?{
        ????public?List findDuplicates(int[] nums) {
        ????????List res = new?ArrayList<>();
        ????????for(int?i = 0;i < nums.length;++i){
        ????????????int?index = Math.abs(nums[i])-1;
        ????????????if(nums[index] < 0){
        ????????????????res.add(index+1);
        ????????????}else?if(nums[index] > 0){
        ????????????????nums[index] *= -1;
        ????????????}
        ????????}
        ????????return?res;
        ????}
        }


        好了,今天的文章就到這里,如果覺(jué)得有所收獲,請(qǐng)順手點(diǎn)個(gè)在看或者轉(zhuǎn)發(fā)吧,你們的支持是我最大的動(dòng)力 。

        上期推文:

        LeetCode1-440題匯總,希望對(duì)你有點(diǎn)幫助!

        LeetCode刷題實(shí)戰(zhàn)441:排列硬幣



        瀏覽 62
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            将军边走边挺进她的h经典语录 | 骚逼淫水视频 | 国产免费视频一区二区裸体 | 亚洲成色A片在线观看5858 | 揉我胸啊嗯~出水了说说 | 女仆脱了个精光被主人摸下面 | 99在线精品视频 | 韩国成人精品三级 | 操逼好爽视频 | 夜夜夜夜夜夜爽噜噜噜噜噜噜 |