【Java】零基础蓝桥杯算法学习——二分查找

算法模板一:

// 数组arr的区间[0,left-1]满足arr[i]=k;
		Scanner scan = new Scanner(System.in);
		int[] arr = {1,2,3,4,5};
		int left = 0,right = arr.length-1;
		int k = scan.nextInt();
		while(left=k) right = mid;
			else left = mid+1;
		}

算法模板二:

// 数组arr的区间[0,left]满足arr[i]<=k,[left+1,n-1]满足arr[i]>k;
		Scanner scan = new Scanner(System.in);
		int[] arr = {1,2,3,4,5,6};
		int left = 0,right = arr.length-1;
		int k = scan.nextInt();
		while(leftk) right = mid-1;
			else left = mid;
		}

例题一:蓝桥杯2018真题:递增三元组

【Java】零基础蓝桥杯算法学习——二分查找_第1张图片

输入示例:

3

1 1 1

2 2 2

3 3 3 

输出示例:27

代码示例:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[] a = new int[n];
        int[] b = new int[n];
        int[] c = new int[n];
        for(int i=0;ib[i]) r=mid;
             else l=mid+1;
        	}
        	if(c[l]>b[i]) B[i]=n-l;
        }
        long[] sum = new long[n+1];
        for(int i=1;i<=n;i++) sum[i]=sum[i-1]+B[i-1];
        long ans=0;
        for(int i=0;ia[i]) r=mid;
             else l=mid+1;
        	}
        	if(b[l]>a[i]) ans+=(sum[n]-sum[l]);
        }
        System.out.println(ans);
        scan.close();
    }
}

例题二:蓝桥杯2017真题:分巧克力

【Java】零基础蓝桥杯算法学习——二分查找_第2张图片

 输出:2

代码示例:

import java.util.Scanner;
public class Main {
     public static void main(String[] args)  {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int k = scan.nextInt();
        int[] h = new int[n];
        int[] w = new int[n];
        for(int i=0;i=k;
    }
}

你可能感兴趣的:(蓝桥杯算法入门学习,算法,java,蓝桥杯)