每日一题6.22

Problem:Consider the following problem:given an array A[1...n]of distinct integers,and a number 1<=k<=n,find any one of the k largest elements in A.For example,if k=2,it is ok to return the largest or second largest integer or second largest largest integer in A,without knowing if the return value is the largest or if it is the second largest array element .Given an algorithm that solves this problem using no more that n-k comparisons of array elements.

题目的大意就是,给定一个k,题目中k=2,返回前k大的数中的任意一个,但是我们不知道这个数是第几大的,因为k=2,所以,要么是第一大,要么是第二大的。我们如何判断返回的这个数是第几大的。

思路:首先以k=2为基准来解决这道题。设置两个标志位,max1,max2.分别代表给定数组中第一大的和第二大的数,将max1,max2与输出的值比较,得到结果即可。

public static int getSecondMax(int[] arrs,int r) throws Exception {
    if (null == arrs || arrs.length <= 1) {
        throw new Exception("数组非法");
    }
    boolean flag=false;
    int max1 = 0, max2 = 0; // 用来记录最大值和第二大的值
    for (int i = 0; i < arrs.length; i++) { // 遍历数组
            if (arrs[i] > max1) { // 当前数据大于最大值
                max2 = max1; // 将max1赋值给max2
                max1 = arrs[i]; // 为max1重新赋值
                flag=true;
            } else { // 当前数据小于最大值
                if (flag) { // max2已经赋值了
                    max2 = Math.max(max2, arrs[i]); // 为max2重新赋值,比较获取较大的值
                } else { // max2没有赋值
                    max2 = arrs[i];
                }
                flag = true; // 修改是否为max2赋值的标记
            }
        }
        if(r==max1){
        return 1;//若代表最大值,则返回1
        }
        return 2;//代表second大的,返回2.
}
如果k为其他值,我的思路是构造大顶堆,根据大顶堆弹出堆顶元素的次数判断返回的值是第几大的。

猜你喜欢

转载自blog.csdn.net/q_all_is_well/article/details/80852510