二分·二分查找
题目传送:hihoCoder - 1128 - 二分·二分查找
解法一:先排个序,然后在进行二分查找,复杂度为O(n*logn) 。
AC代码:
#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <cctype>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define INF 0x7fffffff
using namespace std;
int n, k;
int a[1000005];
int b_search(int x) {
int L = 0, R = n - 1;
while(L <= R) {
int mid = (L + R) >> 1;
if(a[mid] == x) return mid + 1;
else if(a[mid] > x) R = mid - 1;
else if(a[mid] < x) L = mid + 1;
}
return -1;
}
int main() {
while(scanf("%d %d", &n, &k) != EOF) {
for(int i = 0; i < n; i ++) {
scanf("%d", &a[i]);
}
sort(a, a + n);
int ans = b_search(k);
printf("%d\n", ans);
}
return 0;
}
解法二:直接找是否存在k,并且有多少比k小的数,复杂度O(n)。
AC代码:
#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <cctype>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define INF 0x7fffffff
using namespace std;
int n, k, a;
int main() {
scanf("%d %d", &n, &k);
int ans = 0;
int flag = 0;
for(int i = 0; i < n; i ++) {
scanf("%d", &a);
if(a < k) ans ++;
if(a == k) flag = 1;
}
if(flag == 1) {
printf("%d\n", ans + 1);
}
else printf("-1\n");
return 0;
}
二分·二分查找之k小数
题目传送:hihoCoder - 1133 - 二分·二分查找之k小数
解法一:直接先排个序,然后在找第k小数,复杂度为O(n*logn)。
AC代码:
#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <cctype>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define INF 0x7fffffff
using namespace std;
int n, k;
int a[1000005];
int main() {
scanf("%d %d", &n, &k);
for(int i = 1; i <= n; i ++) {
scanf("%d", &a[i]);
}
sort(a + 1, a + n + 1);
if(k > n || k < 1) printf("-1\n");
else printf("%d\n", a[k]);
return 0;
}
解法二:手写一个快排,其中排除掉不需要排序的区间,这样理论上可以达到O(n)的复杂度
AC代码:
#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <cctype>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define INF 0x7fffffff
using namespace std;
int a[1000005];
int n, k;
void Qsort(int *a, int low, int high) {
if(low > k) return;
if(high < k) return;
if(low >= high) return;
int first = low;
int last = high;
int key = a[first];
while(first < last) {
while(first < last && a[last] >= key) last --;
a[first] = a[last];
while(first < last && a[first] <= key) first ++;
a[last] = a[first];
}
a[first] = key;
Qsort(a, low, first - 1);
Qsort(a, first + 1, high);
}
int main() {
scanf("%d %d", &n, &k);
for(int i = 1; i <= n; i ++) {
scanf("%d", &a[i]);
}
Qsort(a, 1, n);
printf("%d\n", a[k]);
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-17 15:39:39