Skip to content

Commit 8f7fe31

Browse files
Refine
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent ef086eb commit 8f7fe31

File tree

2 files changed

+20
-33
lines changed

2 files changed

+20
-33
lines changed

003_longest_substring_without_repeat/longest_substring_without_repeat.c

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,10 @@ static int lengthOfLongestSubstring(char *s)
1515
len++;
1616
} else {
1717
if (index - offset[*s] > len) {
18+
/* not include in substring, go on increasing */
1819
len++;
1920
} else {
21+
/* count from scratch */
2022
len = index - offset[*s];
2123
}
2224
}

004_median_of_two_sorted_array/median_of_two_sorted_array.c

Lines changed: 18 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,27 @@
11
#include <stdio.h>
22
#include <stdlib.h>
33

4-
static double find_kth(int a[], int alen, int b[], int blen, int k)
5-
{
6-
/* Always assume that alen is equal or smaller than blen */
7-
if (alen > blen) {
8-
return find_kth(b, blen, a, alen, k);
9-
}
10-
11-
if (alen == 0) {
12-
return b[k - 1];
13-
}
14-
15-
if (k == 1) {
16-
return a[0] < b[0] ? a[0] : b[0];
17-
}
18-
19-
/* Divide k into two parts */
20-
int ia = k / 2 < alen ? k / 2 : alen;
21-
int ib = k - ia;
22-
if (a[ia - 1] < b[ib - 1]) {
23-
/* a[ia - 1] must be ahead of k-th */
24-
return find_kth(a + ia, alen - ia, b, blen, k - ia);
25-
} else if (a[ia - 1] > b[ib - 1]) {
26-
/* b[ib - 1] must be ahead of k-th */
27-
return find_kth(a, alen, b + ib, blen - ib, k - ib);
28-
} else {
29-
return a[ia - 1];
30-
}
31-
}
32-
334
static double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size)
345
{
35-
int half = (nums1Size + nums2Size) / 2;
36-
if ((nums1Size + nums2Size) & 0x1) {
37-
return find_kth(nums1, nums1Size, nums2, nums2Size, half + 1);
6+
int sum = nums1Size + nums2Size;
7+
int *nums = malloc(sizeof(int) * sum);
8+
int i = 0, j = 0, k = 0;
9+
int half = sum / 2 + 1;
10+
while (k < half) {
11+
int n;
12+
if (i < nums1Size && j < nums2Size) {
13+
n = (nums1[i] < nums2[j]) ? nums1[i++] : nums2[j++];
14+
} else if (i < nums1Size) {
15+
n = nums1[i++];
16+
} else if (j < nums2Size) {
17+
n = nums2[j++];
18+
}
19+
nums[k++] = n;
20+
}
21+
if (sum % 2) {
22+
return nums[k-1];
3823
} else {
39-
return (find_kth(nums1, nums1Size, nums2, nums2Size, half) + find_kth(nums1, nums1Size, nums2, nums2Size, half + 1)) / 2;
24+
return (nums[k-1] + nums[k-2]) / 2.0;
4025
}
4126
}
4227

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy