URL
题目
分析
源码
工程结构
.
└── main_1051.c
源码文件
/* main_1051.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int cmp(const void *pa, const void *pb)
{
return *(int *)pa - *(int *)pb;
}
int height_checker(int *heights, int heights_size)
{
int *exp = (int *)malloc(sizeof(int) * heights_size);
memcpy(exp, heights, sizeof(int) * heights_size);
qsort(exp, heights_size, sizeof(int), cmp);
int ans = 0;
for (int i = 0; i < heights_size; ++i)
{
if (heights[i] != exp[i])
{
++ans;
}
}
free(exp);
return ans;
}
int main()
{
int heights_1[] = {1, 1, 4, 2, 1, 3};
int heights_2[] = {5, 1, 2, 3, 4};
int heights_3[] = {1, 2, 3, 4, 5};
int heights_size = -1;
heights_size = sizeof(heights_1) / sizeof(heights_1[0]);
printf("heights_1 : ");
for (int i = 0; i < heights_size; ++i)
printf("%d ", heights_1[i]);
printf("\nans = %d\n", height_checker(heights_1, heights_size));
heights_size = sizeof(heights_2) / sizeof(heights_2[0]);
printf("heights_2 : ");
for (int i = 0; i < heights_size; ++i)
printf("%d ", heights_2[i]);
printf("\nans = %d\n", height_checker(heights_2, heights_size));
heights_size = sizeof(heights_3) / sizeof(heights_3[0]);
printf("heights_3 : ");
for (int i = 0; i < heights_size; ++i)
printf("%d ", heights_3[i]);
printf("\nans = %d\n", height_checker(heights_3, heights_size));
return 0;
}
LOG参考
heights_1 : 1 1 4 2 1 3
ans = 3
heights_2 : 5 1 2 3 4
ans = 5
heights_3 : 1 2 3 4 5
ans = 0
源码概述
- qsort() 快排,比较即可
小结
快排。