模板--HihoCoder--1133--非有序数组的二分查找

题目链接:https://vjudge.net/problem/HihoCoder-1133/origin

输入

第1行:2个整数N,k。N表示数组长度,
第2行:N个整数,表示a[1..N],保证不会出现重复的数,1≤a[i]≤2,000,000,000。

输出

第1行:一个整数t,表示t在数组中是第k小的数,若K不在数组中,输出-1。

Sample Input
10 4
1732 4176 2602 6176 1303 6207 3125 1 1011 6600
Sample Output
1732

思路一模板:非有序数组的二分查找

思路二:快速排序,快速查找;

int search(int left,int right){
	int ans=-1;
	while(left<=right){
		int w=rand()%(right-left+1)+left;
		swap(a[left],a[w]);
		int temp=a[left],tleft=left,tright=right;
		while(tleft<tright){
			while(tleft<tright&&a[tright]>=temp)	tright--;
			a[tleft]=a[tright];
			while(tleft<tright&&a[tleft]<=temp)		tleft++;
			a[tright]=a[tleft];
		}
		a[tleft]=temp;
		if(tleft==k){	ans=a[tleft];break;}
		else if(tleft>k)	right=tleft-1;
		else left=tleft+1;
	}
	return ans;
}

完整代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
const int maxa=1e7+10;
int n,k; 
int a[maxa];
void read(int &x){
    x=0;bool f=0;
    char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-') f=1;ch=getchar();}
    while(isdigit(ch)) {x=x*10+ch-'0';ch=getchar();}
    x=f?(~x)+1:x;
}
int search(int left,int right){
	int ans=-1;
	while(left<=right){
		int w=rand()%(right-left+1)+left;
		swap(a[left],a[w]);
		int temp=a[left],tleft=left,tright=right;
		while(tleft<tright){
			while(tleft<tright&&a[tright]>=temp)	tright--;
			a[tleft]=a[tright];
			while(tleft<tright&&a[tleft]<=temp)		tleft++;
			a[tright]=a[tleft];
		}
		a[tleft]=temp;
		if(tleft==k){	ans=a[tleft];break;}
		else if(tleft>k)	right=tleft-1;
		else left=tleft+1;
	}
	return ans;
} 
int main(){
	read(n);
	read(k);
	for(int i=1;i<=n;i++)
		read(a[i]);
	printf("%d\n",search(1,n)); 
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
const int maxa=1e7+10;
int n,k; 
int a[maxa];
void read(int &x){
    x=0;bool f=0;
    char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-') f=1;ch=getchar();}
    while(isdigit(ch)) {x=x*10+ch-'0';ch=getchar();}
    x=f?(~x)+1:x;
}
int main(){
	read(n);
	read(k);
	for(int i=1;i<=n;i++)
		read(a[i]);
	sort(a+1,a+1+n);
	printf("%d\n",a[k]);
}

猜你喜欢

转载自blog.csdn.net/queque_heiya/article/details/106185358