whho_0 @ 2024-02-23 17:42:36
#include<iostream>
#include<vector>
using namespace std;
int findx(vector<int> nums,int target,int n) {
int low = 0, high = n;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] >= target) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
if (low > n-1 || nums[low] != target) {
return -1;
}
else {
return low+1;
}
}
int main() {
int n, m;
cin >> n >> m;
vector<int> nums(n);
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
for (int i = 0; i < m; i++) {
int x;
cin >> x;
cout << findx(nums,x,n) << " ";
}
return 0;
}
by TCIC_4294967296 @ 2024-02-23 18:38:01
因为vector在函数传参时会O(n)复制整个数组,普通数组只会传地址,把vector改成引用传递即可。
修改后:
#include<iostream>
#include<vector>
using namespace std;
int findx(vector<int>& nums,int target,int n) {
int low = 0, high = n;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] >= target) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
if (low > n-1 || nums[low] != target) {
return -1;
}
else {
return low+1;
}
}
int main() {
int n, m;
cin >> n >> m;
vector<int> nums(n);
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
for (int i = 0; i < m; i++) {
int x;
cin >> x;
cout << findx(nums,x,n) << " ";
}
return 0;
}
by TCIC_4294967296 @ 2024-02-23 18:39:33
@TCIC_4294967296 亲测可AC