[C Language] Limit the number of searches and output the maximum value found within the number of searches

[C Language] Limit the number of searches and output the maximum value found within the number of searches

1. Topic

You are given an array A of length n. Ask you m times: In the array A, what is the maximum value less than or equal to the given number xi?

input format

  • The first line: two integers n and m, representing the length of the array and the number of searches respectively.
  • The second line: n integers ai, representing each number in the array.
  • Next m lines, each line has an integer xi, which represents the integer to be searched.

output format

  • For each query, output the maximum value less than or equal to xi if it can be found.
  • Otherwise output -1.

Example:

Input:
10 4
1 2 3 3 3 5 5 7 7 9
0
4
9
10
Output:
-1
3
9
9

2. Complete code

#include <iostream>
#include <algorithm>
using namespace std;

int n, m;
int a[100001];

int judge(int input,int a[]) {
    
    
	int res;
	// 查询找不到直接输出-1
	if (input < a[0]) {
    
    
		res = -1;
	}
	// 如果查找数比数组还长,直接输出排序后数组最后一个数
	else if (input >= a[n - 1]) {
    
    
		res = a[n - 1];
	}
	else if (input == a[0]) {
    
    
		res = a[0];
	}
	// 二分查找
	int ans = -1;
	int left = 0, right = n - 1;
	while (left <= right) {
    
    
		// 右移一位
		int mid = (left + right) >> 1;
		if (a[mid] <= input) {
    
    
			ans = a[mid];
			left = mid + 1;
		}
		else {
    
    
			right = mid - 1;
		}
	}
	res = ans;
	return res;
}

int main() {
    
    

	// 数组长度和查找次数
	cin >> n >> m;
	// 输入完整数组
	for (int i = 0; i < n; i++) {
    
    
		cin >> a[i];
	}
	// 数组排序,默认升序
	sort(a, a + n);
	for (int i = 0; i < m; i++) {
    
    
		int x;
		// 输入想查找的数
		cin >> x;
		cout << judge(x, a) << endl;
	}
	return 0;
}

3. Screenshot

insert image description here

Guess you like

Origin blog.csdn.net/a6661314/article/details/125075607