-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path228.summary-ranges.c
More file actions
44 lines (36 loc) · 1011 Bytes
/
228.summary-ranges.c
File metadata and controls
44 lines (36 loc) · 1011 Bytes
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
/*
* @lc app=leetcode id=228 lang=c
*
* [228] Summary Ranges
*/
// @lc code=start
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char **summaryRanges(int *nums, int numsSize, int *returnSize) {
if (numsSize == 0) {
*returnSize = 0;
return NULL;
}
char **ranges = (char **)malloc(numsSize * sizeof(char *));
int rangeCount = 0;
for (int i = 0; i < numsSize; i++) {
int start = nums[i];
int end = nums[i];
while (i < numsSize - 1 && nums[i] + 1 == nums[i + 1]) {
end = nums[i + 1];
i++;
}
if (start == end) {
ranges[rangeCount] = (char *)malloc(13);
snprintf(ranges[rangeCount], 13, "%d", start);
} else {
ranges[rangeCount] = (char *)malloc(25);
snprintf(ranges[rangeCount], 25, "%d->%d", start, end);
}
rangeCount++;
}
*returnSize = rangeCount;
return ranges;
}
// @lc code=end