跳至主要內容

2300. 咒语和药水的成功对数

T4mako算法数组双指针二分查找排序小于 1 分钟

2300. 咒语和药水的成功对数

中等

题目描述open in new window

解题思路:
spells 数组排序,再遍历 potions 数组,在 spells 数组中找到第一个与 potions[i] 相乘大于等于 success 的位置

class Solution {
    public int[] successfulPairs(int[] spells, int[] potions, long success) {
        // 返回结果数组
        int[] res = new int[spells.length];
        // 将 potions 排序
        Arrays.sort(potions);
        for (int i = 0; i < spells.length; i++) {
            int l = 0;
            int r =  potions.length - 1;
            int index = potions.length;
            // 二分查找
            while(l <= r){
                int m = (r - l) / 2 + l;
                if ((long)spells[i] * potions[m] >= success) {
                    r = m - 1;
                    index = m;
                } else {
                    l = m + 1;
                }
            }
            res[i] = potions.length - index;
        }
        return res;
    }
}
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.5