每日一题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为其他值,我的思路是构造大顶堆,根据大顶堆弹出堆顶元素的次数判断返回的值是第几大的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值