题解 | #草原上优势牛种#
草原上优势牛种
https://www.nowcoder.com/practice/178705f48adc4e39ac8537a22e8941cd
1.考察知识点:
数组、排序、哈希表
2.编程语言:
C
3.解题思路:
本题有两种方法,数组和哈希表,哈希表用惯了C++的容器,暂时不会写C的......,
先用数组解决,最简单的方法直接排序,选用冒泡排序,对数组进行排序,最后直接输出中位数即可。
哈希表则是记录每个数字的个数,选出最大的即可!
4.完整代码:
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param numsLen int nums数组长度 * @return int整型 */ #include <stdio.h> void reverse(int *a,int *b) { int temp = 0; temp = *a; *a = *b; *b = temp; } void bub_sort(int *nums,int n) { for(int i=0;i<n-1;i++) { for(int j=0;j+1<n-i;j++) { if(nums[j]>nums[j+1]) { reverse(&nums[j], &nums[j+1]); } } } } int majority_cow(int* nums, int n ) { // write code here bub_sort(nums, n); return nums[n/2]; }#面试高频TOP202#