Blue Bridge Cup algorithm training interval k large number query (Java solution)
Problem Description
Given a sequence, each time it asks which number is the largest number from the lth number to the kth number in the sequence.
Input format
The first line contains a number n, which represents the length of the sequence.
The second line contains n positive integers, representing a given sequence.
The third contains a positive integer m, which represents the number of queries.
In the next m lines, there are three numbers l, r, and K in each line, indicating which of the l-th to r-th numbers of the query sequence from left to right, which is the largest number K from the largest to the smallest. Sequence elements are numbered starting from 1.
Output format
A total of m lines are output, with a number in each line, indicating the answer to the query.
Sample input
5
1 2 3 4 5
2
1 5 2
2 3 2
Sample output
4
2
Data scale and convention
For 30% of the data, n,m<=100;
For 100% data, n,m<=1000;
Ensure that k<=(r-l+1) and the number in the sequence<=106.
Linear selection algorithm implementation
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int n,m;
private static int[] nums;
private static int l,r,k;
public static void main(String[] args) {
n = scanner.nextInt();
nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}
m = scanner.nextInt();
for (int i = 0; i < m; i++) {
l = scanner.nextInt();
r = scanner.nextInt();
k = scanner.nextInt();
int[] numsTemp = new int[r - l + 1];
for (int j = 0; j < r-l+1; j++) {
numsTemp[j] = nums[l-1+j];
}
System.out.println(lineSearch(numsTemp,0,r-l,k));
}
}
/**
* 线性从大到小第几个
* @param arr
*/
private static int lineSearch(int[] arr,int left,int right,int k){
if (left >= right) return arr[left];
int point = arr[left];
int i = left;
int j = right;
while (i < j) {
while (i < j && arr[j] <= point) j--;
arr[i] = arr[j];
while (i < j && arr[i] >= point) i++;
arr[j] = arr[i];
}
if(j - left + 1 == k) return point;
arr[j] = point;
if (j - left + 1 < k) return lineSearch(arr,j+1,right,k-j-1+left);
return lineSearch(arr,left,j-1,k);
}
}