从数组中找出第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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:不使用递归算法找结点||组件
下一篇:unity3d编辑器拖拽创建可拖拽赋值的TextField

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月06日 20时24分18秒