前缀和+Arrays.binarySearch()

2 篇文章 0 订阅

一、Arrays.binarySearch(T[] a, T key)

通过二分法已经排好序的数组中查找指定的元素,并返回该元素的下标
1.如果数组中存在该元素,则会返回该元素在数组中的下标

2.如果数组中不存在该元素,则会返回 -(插入点 + 1)
这里的插入点具体指的是:如果该数组中存在该元素,那个元素在该数组中的下标

import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50, 60};
        //这里在 arr 数组数组中查找,有 30,返回元素 30 所在的索引,即 2
        int index1 = Arrays.binarySearch(arr,30);
        System.out.println("index1 = " + index1);

        //arr 数组中不存在元素 55,返回-(插入点 + 1),即-(5 + 1)
        int index2 = Arrays.binarySearch(arr, 55);
        System.out.println("index2 = " + index2);
    }
}

 二、前缀和

 浅显的来说,就是创建一个数组,用于存储前i项的和

import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        int[] nums = {1,5,3,7,8};
        int[] sums = new int[nums.length + 1];
        //sums为前缀和数组,sums[i] 即 nums数组前i项的和
        for(int i = 1; i <= nums.length; i++) {
            sums[i] = sums[i - 1] + nums[i - 1];
        }

        System.out.println("前缀和数组sums = " + Arrays.toString(sums));
    }
}

输出:

        前缀和数组sums = [0, 1, 6, 9, 16, 24] 

三、LeetCode——#209. 长度最小的子数组

原题链接icon-default.png?t=M276https://leetcode-cn.com/problems/minimum-size-subarray-sum/

给定一个含有 n 个正整数的数组和一个正整数 target 。

找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        //前缀和,arr 为前缀和数组
        int[] arr = new int[nums.length + 1];
        //前 0 项和为0
        arr[0] = 0;

        // arr[i],即 nums 数组前i项的和
        int length = nums.length;
        for(int i = 0; i < length; i++) {
            arr[i + 1] += arr[i] + nums[i];
        }
        
        int res = Integer.MAX_VALUE;
        for(int i = 1; i <= length; i++) {
            int s = target + arr[i - 1];
            int index = Arrays.binarySearch(arr, s);
            if(index < 0) {
                index = -index - 1;
            }   
            if(index <= length) {
                res = Math.min(res, index - i + 1);
            }
        }

        return res == Integer.MAX_VALUE ? 0 : res;
    }
}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值