1. ?LeetCode刷題實(shí)戰(zhàn)141: 環(huán)形鏈表

        共 1544字,需瀏覽 4分鐘

         ·

        2021-01-04 20:32

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

        今天和大家聊的問題叫做?環(huán)形鏈表,我們先來(lái)看題面:
        https://leetcode-cn.com/problems/linked-list-cycle/

        Given head, the head of a linked list, determine if the linked list has a cycle in it.


        There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.


        Return true if there is a cycle in the linked list. Otherwise, return false.

        題意


        給定一個(gè)鏈表,判斷鏈表中是否有環(huán)。
        如果鏈表中有某個(gè)節(jié)點(diǎn),可以通過連續(xù)跟蹤 next 指針再次到達(dá),則鏈表中存在環(huán)。為了表示給定鏈表中的環(huán),我們使用整數(shù) pos 來(lái)表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。如果 pos 是 -1,則在該鏈表中沒有環(huán)。注意:pos 不作為參數(shù)進(jìn)行傳遞,僅僅是為了標(biāo)識(shí)鏈表的實(shí)際情況。
        如果鏈表中存在環(huán),則返回 true 。否則,返回 false 。
        進(jìn)階:你能用 O(1)(即,常量)內(nèi)存解決此問題嗎?


        樣例


        解題


        用一個(gè)hashSet來(lái)存儲(chǔ)已經(jīng)遍歷過的節(jié)點(diǎn)
        一旦發(fā)現(xiàn)某個(gè)節(jié)點(diǎn)的next節(jié)點(diǎn)已經(jīng)被遍歷過,則說(shuō)明存在環(huán)。
        時(shí)間復(fù)雜度和空間復(fù)雜度均是O(n),其中n為鏈表中的節(jié)點(diǎn)個(gè)數(shù)。

        public?class?Solution1?{
        ????public?boolean hasCycle(ListNode head) {
        ????????HashSet hashSet = new?HashSet<>();
        ????????ListNode dummyHead = new?ListNode(-1);
        ????????dummyHead.next = head;
        ????????ListNode cur = dummyHead;
        ????????while(null?!= cur.next){
        ????????????if(hashSet.contains(cur.next)){
        ????????????????return?true;
        ????????????}
        ????????????cur = cur.next;
        ????????????hashSet.add(cur);
        ????????}
        ????????return?false;
        ????}
        }



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

        上期推文:

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


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

        手機(jī)掃一掃分享

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

        手機(jī)掃一掃分享

        分享
        舉報(bào)
          
          

            1. 激情影院一区二区三区 | 免费无遮挡男女交性视频 | 国产999久久久 | 干干操| 色欲欲www成人网站 |