題目:https://leetcode.com/problems/linked-list-cycle-ii/
描述:給定一個鏈結串列,找出串列中迴圈(cycle)開始的node,如果沒有迴圈則回傳null
解題思路:跟141一樣的找迴圈問題,但需要找到迴圈開始的node讓問題變複雜多了。假設用原本的2個快慢pointer方法,最後2個pointer會在圖中2的node上碰面,但我們要找的是圖中1的node
Learn More →
這時慢的pointer走了x+a的步數,快的pointer則走了x+2a+b的步數,由快的比慢的走多一倍步數可以得到2(x+a)=x+2a+b,稍微化簡後就能得出x=b,只要從head走b的步數就能找到1的所在位置了。這時就那麼剛好,從2個pointer碰面的node 2再走b步也會走到node 1的位置,換言之,只要在2個pointer碰面後,讓1個pointer從head開始每次走1格,另1個pointer繼續從node 2位置也每次走1格,這2個pointer下次碰面的位置就會剛好是迴圈開始的node 1了
Learn More →
程式碼:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null) return null;
ListNode node1 = head;
ListNode node2 = head;
while(node2 != null && node2.next != null) {
node1 = node1.next;
node2 = node2.next.next;
if(node1 == node2) break;
}
if(node1 != node2) return null;
node1 = head;
while(node1 != node2) {
node1 = node1.next;
node2 = node2.next;
}
return node1;
}
}
時間複雜度:O(n)
空間複雜度:O(1)
leetcode
medium
linked list
two pointer
題目:https://leetcode.com/problems/power-of-four/description/ 描述:判斷輸入的數字是否為4的次方數 解題思路:標準解法是使用對數基底變換方法,不過這題也可以看作判斷是否為2的次方數的延伸題,4的次方數跟2的次方數一樣用二進位制表示只會有1個位元為1,不過這次這些1只會出現在奇數位上,額外再用一個mask來判斷1是否出現在奇數位即可 程式碼: class Solution { public boolean isPowerOfFour(int n) {
Dec 7, 2022題目:https://leetcode.com/problems/power-of-three/description/ 描述:判斷輸入的數字是否為3的次方數 解題思路(1):用對數的基底變換計算,如果i = log10(n) / log10(3)的i為整數的話代表n為3的次方數 程式碼: class Solution { public boolean isPowerOfThree(int n) {
Dec 7, 2022題目:https://leetcode.com/problems/power-of-two/description/ 描述:判斷輸入的數字是否是2的n次方數 解題思路:有個方法能快速找出正整數n是否為2的n次方數/只有一個位元為1:將n與n-1進行位元AND運算,結果為0則n即為2的n次方數/只有一個位元為1 程式碼: class Solution { public boolean isPowerOfTwo(int n) {
Dec 6, 2022題目:https://leetcode.com/problems/reverse-bits/ 描述:將32位元的unsigned int中的位元順序顛倒後回傳結果的值 解題思路:詳細解答來源,用分治法(divide and conquer)每次將處理範圍中左半與右半邊的位元值互換,對一個有2^n位元的數字總共只需要換n次即可 程式碼: public class Solution { // you need treat n as an unsigned value
Nov 30, 2022or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up