Skip to content

Commit c35ed45

Browse files
authored
Create (数组操作)1051、高度检查器
1 parent d532b5e commit c35ed45

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
学校在拍年度纪念照时,一般要求学生按照 非递减 的高度顺序排列。
3+
4+
请你返回至少有多少个学生没有站在正确位置数量。该人数指的是:能让所有学生以 非递减 高度排列的必要移动人数。
5+
6+
 
7+
8+
示例:
9+
10+
输入:[1,1,4,2,1,3]
11+
输出:3
12+
解释:
13+
高度为 4、3 和最后一个 1 的学生,没有站在正确的位置。
14+
 
15+
16+
提示:
17+
18+
1 <= heights.length <= 100
19+
1 <= heights[i] <= 100
20+
*/
21+
22+
int cmp(const void* a, const void* b)
23+
{
24+
return *(int*)a - *(int*)b;
25+
}
26+
27+
int heightChecker(int* heights, int heightsSize)
28+
{
29+
int* origin_heights = (int*)malloc(heightsSize * sizeof(int));
30+
int cnt = 0;
31+
memcpy(origin_heights, heights, heightsSize * sizeof(heights[0]));
32+
qsort(heights, heightsSize, sizeof(int), cmp);
33+
34+
for(int i = 0; i < heightsSize; i++)
35+
{
36+
if(heights[i] != origin_heights[i])
37+
cnt++;
38+
}
39+
40+
return cnt++;
41+
}
42+
43+
/*
44+
思路简单:
45+
1、对给定数组按照非递减顺序排序;
46+
2、遍历非递减数组和原数组,对应位置元素不相等的即为要移动的元素。
47+
*/

0 commit comments

Comments
 (0)