auto commit
This commit is contained in:
parent
0fc0c4df8b
commit
9daabd52bf
|
@ -1672,14 +1672,24 @@ private void merge(int[] a, int start, int mid, int end) {
|
|||
|
||||
## 52. 两个链表的第一个公共结点
|
||||
|
||||
```html
|
||||
A: a1 → a2
|
||||
↘
|
||||
c1 → c2 → c3
|
||||
↗
|
||||
B: b1 → b2 → b3
|
||||
```
|
||||
|
||||
设 A 的长度为 a + c,B 的长度为 b + c,其中 c 为尾部公共部分长度,可知 a + c + b = b + c + a。
|
||||
|
||||
当访问 A 链表的指针访问到链表尾部时,令它从链表 B 的头部开始访问链表 B;同样地,当访问 B 链表的指针访问到链表尾部时,令它从链表 A 的头部开始访问链表 A。这样就能控制访问 A 和 B 两个链表的指针能同时访问到交点。
|
||||
|
||||
```java
|
||||
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
|
||||
ListNode l1 = pHead1, l2 = pHead2;
|
||||
while (l1 != l2) {
|
||||
if (l1 == null) l1 = pHead2;
|
||||
else l1 = l1.next;
|
||||
if (l2 == null) l2 = pHead1;
|
||||
else l2 = l2.next;
|
||||
l1 = (l1 == null) ? pHead2 : l1.next;
|
||||
l2 = (l2 == null) ? pHead1 : l2.next;
|
||||
}
|
||||
return l1;
|
||||
}
|
||||
|
@ -1690,15 +1700,16 @@ public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
|
|||
## 53 数字在排序数组中出现的次数
|
||||
|
||||
```java
|
||||
public int GetNumberOfK(int[] array, int k) {
|
||||
public int GetNumberOfK(int[] array, int num) {
|
||||
int l = 0, h = array.length - 1;
|
||||
// 先找出 num 在数组最左端的位置,可以控制二分查找结束时 l 指向该位置
|
||||
while (l <= h) {
|
||||
int m = l + (h - l) / 2;
|
||||
if (array[m] >= k) h = m - 1;
|
||||
if (array[m] >= num) h = m - 1;
|
||||
else l = m + 1;
|
||||
}
|
||||
int cnt = 0;
|
||||
while (l < array.length && array[l++] == k) cnt++;
|
||||
while (l < array.length && array[l++] == num) cnt++;
|
||||
return cnt;
|
||||
}
|
||||
```
|
||||
|
@ -1710,17 +1721,16 @@ TreeNode ret;
|
|||
int cnt = 0;
|
||||
|
||||
TreeNode KthNode(TreeNode pRoot, int k) {
|
||||
inorder(pRoot, k);
|
||||
inOrder(pRoot, k);
|
||||
return ret;
|
||||
}
|
||||
|
||||
private void inorder(TreeNode root, int k) {
|
||||
if (root == null) return;
|
||||
if (cnt > k) return;
|
||||
inorder(root.left, k);
|
||||
private void inOrder(TreeNode root, int k) {
|
||||
if (root == null || cnt > k) return;
|
||||
inOrder(root.left, k);
|
||||
cnt++;
|
||||
if (cnt == k) ret = root;
|
||||
inorder(root.right, k);
|
||||
inOrder(root.right, k);
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -1861,11 +1871,11 @@ private void reverse(char[] c, int start, int end) {
|
|||
对于一个给定的字符序列 S,请你把其循环左移 K 位后的序列输出。例如,字符序列 S=”abcXYZdef”, 要求输出循环左移 3 位后的结果,即“XYZdefabc”。
|
||||
|
||||
```java
|
||||
public String LeftRotateString(String str, int n) {
|
||||
public String LeftRotateString(String str, int k) {
|
||||
if (str.length() == 0) return "";
|
||||
char[] c = str.toCharArray();
|
||||
reverse(c, 0, n - 1);
|
||||
reverse(c, n, c.length - 1);
|
||||
reverse(c, 0, k - 1);
|
||||
reverse(c, k, c.length - 1);
|
||||
reverse(c, 0, c.length - 1);
|
||||
return new String(c);
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user