主要的想法就是把陣列左右加寬,就不用考慮邊界
然後再慢慢for迴圈
C++ code
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<int> a(n+2);
for (int i = 1; i < n+1; i++) {
cin >> a[i];
}
a[0]=INT_MAX;a[n+1]=INT_MAX;
int c;
cin >> c;
int l, r;
int lx, rx;
for (int i = c - 1; i >= 0; i--) {
if (a[i] > a[i + 1]) {
l = a[i + 1];
lx = i + 1;
break;
}
}
for (int i = c+1; i < n+2; i++) {
if (a[i] > a[i - 1]) {
r = a[i - 1];
rx = i - 1;
break;
}
}
if (r < l) {
cout << rx;
}else{
cout<<lx;
}
}