diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /height_checker.c | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'height_checker.c')
-rw-r--r-- | height_checker.c | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/height_checker.c b/height_checker.c new file mode 100644 index 0000000..a752d9f --- /dev/null +++ b/height_checker.c @@ -0,0 +1,38 @@ +// 1051. Height Checker +#include "leetcode.h" + +/* + * a school is trying to take an annual photo of all the students. the students + * are asked to stand in a single file line in non decreasing order by height. + * let this ordering be represented by the integer array 'expected' where + * 'expected[i]' is the expected height of the i'th student in line. you are + * given an integer array 'heights' representing the current order that the + * students are standing in. each 'heights[i]' is the height of the i'th student + * in line. return the number of indices where 'heights[i] != expected[i]' + */ + +int cmp(const void *a, const void *b) { + long aa = *(int *)a, bb = *(int *)b; + return aa - bb; +} + +int heightChecker(int *heights, int heightsSize) { + if (heightsSize < 2) + return 0; + int *expected = (int *)malloc(sizeof(int) * heightsSize); + memcpy(expected, heights, sizeof(int) * heightsSize); + qsort(expected, heightsSize, sizeof(int), cmp); + int diff = 0; + for (int i = 0; i < heightsSize; i++) + if (heights[i] != expected[i]) + diff++; + free(expected); + return diff; +} + +int main() { + int h1[] = {1, 1, 4, 2, 1, 3}, h2[] = {5, 1, 2, 3, 4}, h3[] = {1, 2, 3, 4, 5}; + printf("%d\n", heightChecker(h1, ARRAY_SIZE(h1))); // expect: 3 + printf("%d\n", heightChecker(h2, ARRAY_SIZE(h2))); // expect: 5 + printf("%d\n", heightChecker(h3, ARRAY_SIZE(h3))); // expect: 0 +} |