你如何找到第二个最高数量的一个整数数组? [英] How do you find second highest number in an integer array?

查看:102
本文介绍了你如何找到第二个最高数量的一个整数数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何找到第二个最高数量的一个整数数组?

这是一个很好的执行?

有没有更好的方式来做到这一点?

 公共类Find2ndHighest {
    公共静态无效的主要(字串[] args){
        INT B〔] = {2,3,1,0,5};

        TreeMap的<整数,整数GT;树=新TreeMap的<整数,整数GT;();
        的for(int i = 0; I< b.length个;我++){
            tree.put(二[I],0);
        }
        的System.out.println(tree.floorKey(tree.lastKey() -  1));
    }
}
 

解决方案

您可以排序数组并获取其在O(nlogn)执行倒数第二个元素,但是这只有当你确定没有重复的阵列否则这方法是不可靠的。

您可以通过遍历数组保持计数器最高和第二高,并返回第二高。这将执行O(N)

例如:

  INT最高= Integer.MIN_VALUE的+ 1;
 INT sec_highest = Integer.MIN_VALUE的;
 对于(INT I:B)// b为整数数组
 {
     如果(I>最高)
     {
        sec_highest最高=; //使当前的最高到第二位
        最高= I; //使电流值最高
     }
     否则,如果(I> sec_highest和放大器;&安培;!I =最高)
     {
        sec_highest =我;
     }
 }
 

How do you find second highest number in an integer array?

Is this a good implementation?

Is there a better way to do this?

public class Find2ndHighest {
    public static void main(String[] args) {
        int b[] = {2,3,1,0,5};

        TreeMap<Integer,Integer> tree = new TreeMap<Integer,Integer>();
        for(int i = 0; i<b.length;i++){
            tree.put(b[i], 0);
        }
        System.out.println(tree.floorKey(tree.lastKey()-1));
    }
}

解决方案

You can sort the array and fetch second last element which executes in O(nlogn), but this works only if you are sure that there are no duplicates in the array else this method is unreliable.

You can iterate through the array maintain counters for highest and second highest and return 2nd highest. This executes in O(n)

Example:

 int highest = Integer.MIN_VALUE+1; 
 int sec_highest = Integer.MIN_VALUE;
 for(int i : b) //b is array of integers
 {
     if(i>highest)
     {
        sec_highest = highest; //make current highest to second highest
        highest = i; //make current value to highest
     }
     else if(i>sec_highest && i != highest) 
     {
        sec_highest = i;
     }
 }

这篇关于你如何找到第二个最高数量的一个整数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆