リングチェーンテーブル入口_チェーンテーブルを反転_連結順序チェーンテーブル_ツリーのサブ構造
15078 ワード
23剣指Offer_23_チェーンテーブルのリングの入口ノード
24剣指Offer_24_チェーンテーブルを反転
25剣指Offer_25_2つのソートされたチェーンテーブルをマージ
26剣指Offer_26_ツリーのサブ構造
/**
* https://leetcode-cn.com/problems/linked-list-cycle-ii/
*
* @author Qitong!!
* @Date 2020/7/22
*/
public class Offer_23_ {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null || head.next.next == null) return null;
ListNode slow = head.next;
ListNode fast = head.next.next;
//
while (slow != fast) {
if (fast.next == null || fast.next.next == null) {
return null;
}
slow = slow.next;
fast = fast.next.next;
}
// !
fast = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
24剣指Offer_24_チェーンテーブルを反転
/**
* https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
*
* @author Qitong!!
* @Date 2020/7/2
*/
public class Offer_24_ {
// O(N) O(N)
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
// ! O(N) O(1)
public ListNode reverseList2(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = null;
while (head != null) {
ListNode tmp = head.next;
head.next = newHead;
newHead = head;
head = tmp;
}
return newHead;
}
25剣指Offer_25_2つのソートされたチェーンテーブルをマージ
/**
* https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
*
* @author Qitong!!
* @Date 2020/7/2
*/
public class Offer_25_ {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode dummyHead = new ListNode(0);
ListNode dummyTail = dummyHead;
while (l1 != null && l2 != null) {
if (l1.val >= l2.val) {
dummyTail.next = l2;
l2 = l2.next;
} else {
dummyTail.next = l1;
l1 = l1.next;
}
dummyTail = dummyTail.next;
}
if (l1 != null) {
dummyTail.next = l1;
}
if (l2 != null) {
dummyTail.next = l2;
}
return dummyHead.next;
}
}
26剣指Offer_26_ツリーのサブ構造
/**
* https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/
*
* @author Qitong!!
* @Date 2020/7/2
*/
public class Offer_26_ {
// , !!
public boolean isSubStructure(TreeNode A, TreeNode B) {
if (A == null || B == null) return false;
return recur(A,B)||isSubStructure(A.left,B)||isSubStructure(A.right,B);
}
private boolean recur(TreeNode A,TreeNode B){
if (B == null) return true;
if (A == null || A.val != B.val) return false;
return recur(A.left, B.left)&&recur(A.right,B.right);
}
}