练习题
977.有序数组的平方
209.长度最小的子数组
59.螺旋矩阵II
977.有序数组的平方
1、自己看到题目的第一想法:(思路1)先算平方,后qsort排序
2、知识点:qsort排序
【qsort排序】
// 1、对int数组进行排序(从小到大)
int num[100];
int cmp(const void *a, const void *b)
{
return (*(int*)a - *(int*)b);
}
qsort(num,100,sizeof(num[0]), cmp);
// 2、对char数组进行排序
char word[100];
int cmp(const void* a, const void* b)
{
return (*(char*)a - *(char*)b);
}
qsort(word, 100, sizeof(word[0]), cmp);
// 3、对double进行排序
double num[100];
int cmp(const void* a, const void* b)
{
return (*(double*)a > *(double*)b ? 1: -1);
}
qsort(num, 100, sizeof(num[0]), cmp);
// 4、对结构体进行排序
struct body{
int x;
int y;
} s[100];
// 按照x从小到大排序,当X相同的时候按照y从大到小排序
int cmp(const void* a, const void* b)
{
struct body* c = (struct body*)a;
struct body* d = (struct body*)b;
if (c->x != d->x) {
return (c->x - d->x);
} else {
return (d->y - c->y);
}
}
// 5、对字符串进行排序
struct body {
int data;
char str[100];
} s[100];
// 按照结构体中字符串str的字典顺序排序
int cmp(const void* a, const void* b)
{
return strcmp((*(struct body*)a)->str, (*(struct body*)b)->str);
}
// 6、二维数组的qsort排序
int cmp(const void* a, const void* b)
{
int *x = *(int **)a;
int *y = *(int **)b;
return (x[0] - y[0]);
}
qsort(commSlots,commSlotCnt,sizeof(int*), cmp);
209.长度最小的子数组
知识点:
C/C++中的 <limits.h> 头文件中定义:
#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX - 1)
INT_MAX为 2^31-1 ,即 2147483647 ;
INT_MIN为 -2^31 , 即 2147483648 ;
刷题记录:
思路1:暴力计算,然后获取最小长度,并返回
缺点:超时
思路2: 滑窗
结果:很快能通过
59.螺旋矩阵II
【知识点】二维数组的申请释放
int **box = calloc(n, sizeof(int*));
// 注意判空(暂略)
if (box == NULL) {
return NULL;
}
*returnColumnSizes = calloc(n, sizeof(int));
for (int idx = 0; idx < n; idx++) {
box[idx] = calloc(n, sizeof(int));
// 注意判空和内存释放保护(暂略)
(*returnColumnSizes)[idx] = n;
}
*returnSize = n;
.....
return box;