-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path228. Summary Ranges.c
79 lines (66 loc) · 1.67 KB
/
228. Summary Ranges.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
228. Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
void ranges(int *nums, int numsz, int ***pp, int *sz, int *n) {
int a, b;
int i, l;
char buff[64];
if (numsz == 0) return;
if (*n == *sz) {
(*sz) *= 2;
(*pp) = realloc(*pp, (*sz) * sizeof(char *));
//assert(*pp);
}
b = a = nums[0];
i = 1;
while (i < numsz && (b + 1) == nums[i]) {
i ++; b ++;
}
l = sprintf(buff, "%d", a);
if (i > 1) {
l += sprintf(&buff[l], "->%d", b);
}
(*pp)[*n] = malloc((l + 1) * sizeof(char));
strcpy((*pp)[*n], buff);
(*n) ++;
ranges(&nums[i], numsz - i, pp, sz, n);
}
char** summaryRanges(int* nums, int numsSize, int* returnSize) {
int sz, n;
char **p;
*returnSize = 0;
if (numsSize == 0) return NULL;
sz = 100;
p = malloc(sz * sizeof(char *));
//assert(p);
n = 0;
ranges(nums, numsSize, &p, &sz, &n);
*returnSize = n;
return p;
}
/*
Difficulty:Medium
Total Accepted:81.3K
Total Submissions:273.2K
Companies Google
Related Topics Array
Similar Questions
Missing Ranges
Data Stream as Disjoint Intervals
*/