从数组中找出第n大的数
发布日期:2022-03-03 10:44:00
浏览次数:11
分类:技术文章
本文共 1604 字,大约阅读时间需要 5 分钟。
基本思路就是随便找一个数,遍历数组,比这个数大的那么放到这个数的左边,比这个数小的放在这个数的右边。如果左边的数+1 == 这个n 那么当前这个数就是我们需要返回的,否则遍历左侧或者右侧的数组,条件是 如果左边的数很少,比如只有1个 ,你需要得到第3大的数,明显需要遍历右侧,否则就遍历左侧 。如此递归进行
public static class Util
{
public static int INVALID_INT_VALUE = 1 << 31;
//nStartIndex为数组开始的索引 nArrayLength为数组的长度 k为第k大的数 public static int FindMaxValueN(int[] array,int nStartIndex, int nArrayLength, int k) { if(nStartIndex < 0 || nArrayLength > array.Length || k > array.Length) { return INVALID_INT_VALUE; } int refValue = array[nStartIndex]; int nLeftCount = 0; for(int i = nStartIndex; i < nStartIndex + nArrayLength; i++) { if(refValue < array[i] ) { int recordValue = array[i]; for(int j = i-1; j >= 0; j--) { array[j + 1] = array[j]; } array[nStartIndex] = recordValue; ++nLeftCount; } } if (nLeftCount == k - 1) { return array[nStartIndex + k-1]; } else if (nLeftCount > k - 1) { //遍历左测 return FindMaxValueN(array, nStartIndex, nLeftCount, k ); } else { //遍历右测 return FindMaxValueN(array, nStartIndex + nLeftCount + 1, nArrayLength - nLeftCount -1,k - nLeftCount - 1 ); } }}
//测试用例
static void Main2(string[] args)
{ Console.WriteLine((5 << 2) & 6); int[] a = { 1, 2, 3, 4, 5 }; int[] b = { 5, 4, 3, 2, 1 }; int[] c = { 1, 5, 3, 4, 2 }; int[] d = { 2, 3, 1, 4, 5 }; for(int i = 0; i < 5; i++) { Console.WriteLine("-------第" + (i+1) + "大的数为"); Console.WriteLine( Util.FindMaxValueN(a, 0, a.Length, i+1)); Console.WriteLine(Util.FindMaxValueN(b, 0, b.Length, i+1)); Console.WriteLine(Util.FindMaxValueN(c, 0, c.Length, i+1)); Console.WriteLine(Util.FindMaxValueN(d, 0, d.Length, i+1)); Console.WriteLine("-------end"); } Console.ReadKey(); }转载地址:https://blog.csdn.net/yangjie6898862/article/details/119900434 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2024年04月06日 20时24分18秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
SAP Commerce(原Hybris)的一些架构图,持续更新
2019-04-27
如何使用R语言在SAP Analytics Cloud里绘制各种统计图表
2019-04-27
阿里云上的docker安装
2019-04-27
重新安装SCCM 2012 client,解决Windows10 1909在线更新问题
2019-04-27
使用jasmine.createSpyObj具有依赖关系的Angular服务进行单元测试
2019-04-27
MAYA 绑定 批量 关联属性 (手指FK 2 SK)
2019-04-27
c语言格式化浮点数多余的0
2019-04-27
Linux快速创建文件命令
2019-04-27
Linux下挂载U盘
2019-04-27
ubtunu开机黑屏无桌面解决方法
2019-04-27
Linux开发_退格符的花样用法
2019-04-27
Linux开发_判断程序是否以管理员权限运行(root/sudo)
2019-04-27
Windows核心编程_实现QQ好友来消息时任务栏头像闪烁功能
2019-04-27
CMake构建_增加编译选项(debug&&release)
2019-04-27
Cmake构建_指定gcc/g++版本
2019-04-27
Cmake构建_设置全局编译选项
2019-04-27
Cmake构建_设置debug与release不同名字
2019-04-27
Cmake构建_设置debug与release输出路径
2019-04-27