LC5450.满足条件的子序列数目(双指针)

问题

在这里插入图片描述在这里插入图片描述

解题

  • 看清题干,是最小值和最大值的和小于等于target,因此组合中的最大值和最小值之间的数应该在最大值和最小值之间,因此先对数组排序。
  • 排序之后对每一个最小值i,找到最大的且满足条件的值j。那么这个最小值和最大值之间的数的个数(j - i - 1)可以贡献2^(j - i)个组合。
  • 预处理2的幂次数组,防止溢出。
class Solution {
    public int numSubseq(int[] nums, int target) {
        int mod = 1000000007;
        int MAXLEN = 100050;
        int[] binValue = new int[MAXLEN];
        binValue[0] = 1;
        int n = nums.length;
        
        for(int i = 1; i <= n; i ++){//预处理,都 % mod
            binValue[i] = (binValue[i - 1] + binValue[i - 1]) % mod;
        }
        
        Arrays.sort(nums);
        int res = 0;
        for(int i = 0, j = n - 1; i <= j; i ++){
        	//找到最大的且满足条件的nums[j]
            while(j >= i && nums[i] + nums[j] > target) --j;
            int cnt = j - i;//最大值和最小值之间的数+1
            if(cnt >= 0){
                res = (res + binValue[cnt]) % mod;
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41423750/article/details/107007786