这道题其实和用最小数量箭引爆气球一样,代码差不多,都是求重叠区间的量
int cmp(const void *a,const void *b)
{
return ((*((int**)a))[0] > (*((int**)b))[0]);
}
int eraseOverlapIntervals(int** intervals, int intervalsSize, int* intervalsColSize) {
if(intervalsSize == 0)
return 0;
qsort( intervals, intervalsSize, sizeof( intervals[0]),cmp);
int result = 0;
int i = 1;
for(i = 1; i < intervalsSize; i++) {
if(intervals[i][0] >= intervals[i-1][1])
continue;
else
result++;
intervals[i][1] = intervals[i][1] > intervals[i-1][1] ? intervals[i-1][1] : intervals[i][1];
}
return result;
}
局部最优:就时找这个区间字母中的最远位置,
如何找到这个最远的位置?
——可以用哈希表来记录
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* partitionLabels(char* s, int* returnSize) {
int hash[27] ={0};
for(int i = 0; i < strlen(s); s++){
hash[s[i] - 'a'] = i;
}
int* ans = (int*)malloc(sizeof(int) * 500);
*returnSize = 0;
int start = 0, end = 0;
for(int j = 0; j < strlen(s); j++){
end = fmax(end, hash[s[i] - 'a']);
if (i == end) {
partition[(*returnSize)++] = end - start + 1;
start = end + 1;
return partition;
}
错误:没有正确的认识到这个hash这记录的是位置,不是距离,要用 end - start + 1;表示
重叠区间其实代码都是相类似的,判断条件都大体不差,有区别的是要进行什么样的操作
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume
* caller calls free().
*/
int cmp(const void* a, const void* b) {
return ((*((int**)a))[0] > (*((int**)b))[0]);
}
// 合并区间函数
int** merge(int** intervals, int intervalsSize, int* intervalsColSize, int* returnSize, int** returnColumnSizes) {
int** result = NULL;
*returnSize = 0;
*returnColumnSizes = NULL;
if (intervalsSize == 0) {
return result;
}
result = (int**)malloc(intervalsSize * sizeof(int*));
*returnColumnSizes = (int*)malloc(intervalsSize * sizeof(int));
qsort(intervals, intervalsSize, sizeof(intervals[0]), cmp);
result[*returnSize] = (int*)malloc(2 * sizeof(int));
result[*returnSize] = intervals[0];
(*returnColumnSizes)[*returnSize] = 2;
(*returnSize)++;
for (int i = 1; i < intervalsSize; i++) {
if (result[*returnSize - 1][1] >= intervals[i][0]) {
result[*returnSize - 1][1] =
(result[*returnSize - 1][1] > intervals[i][1]) ? result[*returnSize - 1][1] : intervals[i][1];
} else {
result[*returnSize] = (int*)malloc(2 * sizeof(int));
result[*returnSize] = intervals[i];
(*returnColumnSizes)[*returnSize] = 2;
(*returnSize)++;
}
}
return result;
}