腾讯笔试题 微信红包

春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现,某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。写出具体算法思路和代码实现,要求算法尽可能高效。
给定一个红包的金额数组gifts及它的大小n,请返回所求红包的金额。
测试样例:
[1,2,3,2,2],5
返回:2

/**
 * 超过一半,如果存在,中位数就是.
 * Created by ustc-lezg on 16/4/7.
 */
public class Solution {

    public int getValue(int[] gifts, int n) {
        return quickSort(gifts, 0, n - 1);
    }

    public int quickSort(int[] arr, int low, int high) {
        int mid = (high + 1) >> 1;
        int pivot = partition(arr, low, high);
        while (pivot != mid) {//利用快排找到中位数
            if (pivot < mid) {
                pivot = partition(arr, pivot + 1, high);
            } else {
                pivot = partition(arr, low, pivot - 1);
            }
        }
        int res = arr[pivot];
        if (!check(arr, high + 1, res)) {
            return 0;
        }
        return res;
    }

    public int partition(int arr[], int low, int high) {
        int left = low;
        int right = high;
        int temp = arr[low];
        while (left < right) {
            while (left < right && arr[right] >= temp) {
                --right;
            }
            if (left < right) {
                arr[left] = arr[right];
            }
            while (left < right && arr[left] <= temp) {
                ++left;
            }
            if (left < right) {
                arr[right] = arr[left];
            }
        }
        arr[left] = temp;
        return left;
    }

    public boolean check(int[] arr, int n, int res) {
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i] == res) {
                ++count;
            }
        }
        if (count * 2 <= n) {
            return false;
        } else {
            return true;
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值