雙指標問題總結

2021-10-07 06:30:39 字數 2724 閱讀 7097

左右指標的常見演算法

雙指標分為兩類,快慢指標和左右指標,前者主要解決鍊錶問題,後者主要解決陣列問題。

環問題

public

boolean

hascycle

(listnode head)

listnode fast = head;

listnode slow = head;

while

(fast != null && fast.next != null)

}return

false

;}

public listnode detectcycle

(listnode head)

listnode intersect=

getintersect

(head);if

(intersect==null)

listnode fast=head;

listnode slow=intersect;

while

(fast!=slow)

return fast;

}//返回快慢指標的相遇點

public listnode getintersect

(listnode head)

listnode fast=head;

listnode slow=head;

while

(fast!=null&&fast.next!=null)

}return null;

}

尋找鍊錶某點問題
public

static listnode midnode

(listnode node)

return slow;

}

public listnode getkthfromend

(listnode head,

int k)

listnode fast = head;

listnode slow = head;

while

(k >1)

k--;}

while

(fast != null && fast.next != null)

return slow;

}

去除重複元素

二分查詢

二分查詢是左右指標的典型,有遞迴版和非遞迴版兩種實現

public

intsearch

(int

nums,

int target)

return

search

(nums,

0, n -

1, target);}

public

intsearch

(int

nums,

int left,

int right,

int target)

int mid = left +

((right - left)

>>1)

;if(nums[mid]

< target)

else

if(nums[mid]

> target)

else

}

public

intsearch

(int

nums,

int target)

int left =0;

int right = n -1;

while

(left <= right)

else

if(nums[mid]

> target)

else

}return-1

;}

兩數之和

給定乙個公升序排列的有序陣列,找到兩個數,使他們相加之和等於目標數

有序陣列很容易聯想到二分,這道題可以用二分的思想去解決,慢慢逼近最終值。

public

int[

]twosum

(int

numbers,

int target);}

else

if(sum > target)

else

}return

newint

;}

反轉陣列

陣列末尾位置很容易通過索引進行定位。 所以可以根據不斷前後對調來實現反轉陣列。

public

int[

]reverse

(int

nums)

return nums;

}

驗證回文子串

歸併兩個有序陣列

public

void

merge

(int

nums1,

int m,

int[

] nums2,

int n)

while

(j >=0)

}

滑動視窗

滑動視窗是雙指標解決問題的高階應用。

雙指標問題

雙指標可用於多種情景之下,用於查詢陣列中滿足條件的數,coding utf 8 查詢三個數加起來等於0 def findthreesum nums,target 0 nums.sort res for left in xrange nums.len if left 0 and nums left n...

雙指標問題

雙指標一般有兩種case 1.快慢指標,一般排序需要使用快慢指標,快慢指標有兩種遊走方式 1.快指標一直往前,不歸位 2.慢指標移動時,快指標歸位。2.收尾指標,一般回文 對稱性判斷需要使用首尾指標 雙指標中,快慢指標問題 1.指標一快一慢,快指標按序遍歷陣列,慢指標記錄有效資料位置。2.當快指標找...

雙指標技巧總結

我把雙指標技巧再分為兩類,一類是 快慢指標 一類是 左右指標 前者解決主要解決鍊錶中的問題,比如典型的判定鍊錶中是否包含環 後者主要解決陣列 或者字串 中的問題,比如二分查詢。一 快慢指標的常見演算法 快慢指標一般都初始化指向鍊錶的頭結點 head,前進時快指標 fast 在前,慢指標 slow 在...