LeetCode. Breakfast combination (Java) sort + binary search

Xiaokou chose a breakfast stall in the autumn market. The price of each staple food is recorded in the one-dimensional integer array staple, and the price of each beverage is recorded in the one-dimensional integer array drinks. The Xiaokou plan chooses one staple food and one beverage, and the cost does not exceed x yuan. Please return how many purchase options there are in the small deduction.

Note: The answer needs to be modulo 1e9 + 7 (1000000007), such as: the initial result of the calculation is: 1000000008, please return 1

Master: Binary search: Return the subscript of the first keyword found in binary search, regardless of whether there are the same keywords later, because we are binary; if there is no such keyword, insert and return -index-1, Indicates where to insert.
Idea: If you want to divide into two, sort first.
Then first find the subscript of <=x in the Staple array (the keyword for binary search here is 1 greater than the "cost not more than" x required by the title, so that it is avoided: multiple keywords with the same value, but only the previous one is returned Ignore the latter case; the last subscript is moved forward one is the subscript that meets the requirements)
In the loop, through target = x-staple[i] to find the largest subscript tempDrinks that meets the drinks. The value of tempDrinks+1 is the purchase plan of drinks corresponding to the current staple[i].

class Solution {
    
    
  public int breakfastNumber(int[] staple, int[] drinks, int x) {
    
    
		Arrays.sort(staple);
		Arrays.sort(drinks);
		/*
		 * 二分查栈要考虑两种情况: 一种是本身存在关键字,返回第一个关键字的下标,但后面可能也存在相同的关键字——解决方法:找比关键字略大一个的数
		 * 一种是不存在关键字,返回硬插入元素的下标
		 */
		long count = 0;
		int index = Arrays.binarySearch(staple, x + 1);
		if (index < 0) {
    
    
			index = (index + 1) * (-1);
		}
		index--;
		for (int i = 0; i <= index; i++) {
    
    
			int tempDrinks = Arrays.binarySearch(drinks, x - staple[i]);
			// 考虑后面也存在相同关键字的可能
			if (tempDrinks < 0) {
    
    
				tempDrinks = (tempDrinks + 1) * (-1);
				tempDrinks--;
			} else {
    
    
				while (tempDrinks < drinks.length-1 && drinks[tempDrinks] == drinks[tempDrinks + 1]) {
    
    
					tempDrinks++;
				}
			}
			count += tempDrinks + 1;
			count %= 1000000007;
		}
		return (int) count;
	}
}

end.

Guess you like

Origin blog.csdn.net/weixin_44998686/article/details/108894106