zoukankan      html  css  js  c++  java
  • 选择问题(线性时间复杂度)

            採用分治策略找出第K小的元素!要求程序的时间复杂度为线性函数。

    #include<iostream>
    #include<iterator>
    #include<algorithm>
    #include<time.h>
    #include<vector>
    using namespace std;
    
    /*
    *选择问题(线性时间复杂度)
    *在beg和end之间查找第k个元素
    */
    int Fast_find(vector<int> &vec,int beg,int end,int k)
    {
    	if(k>end||k<beg+1)
    		throw range_error("输入的參数错误");
    	if(beg+1>=end)
    	{
    			return vec[beg];
    	}
    	int i ,j;
    	for (i = beg,j = end; i < j; )
    	{
    		do
    		{
    			j--;
    		} while (vec[j]>vec[beg]);
    		do
    		{
    			i++;
    		}while(i<end&&vec[i]<vec[beg]);
    		if(i<j)
    			swap(vec[i],vec[j]);
    	}
    	swap(vec[beg],vec[j]);
    	if(j==k-1) return vec[j];
    	if(j>k-1)  return Fast_find(vec,beg,j,k);
    	if(j<k-1)  return Fast_find(vec,j+1,end,k);
    }
    int main()
    {
    	vector<int> vec;
    	copy(istream_iterator<int>(cin),istream_iterator<int>(),back_inserter(vec));
    	cin.clear();
    	
    	int k ;
    	cout<<"输入查找第几个元素(从小到大)!"<<endl;
    	cin>>k;
    
    	long start, end;
    	int res;
    	start = clock();
    	try
    	{
    	 res = Fast_find(vec,0,vec.size(),k);
    	}
    	catch(range_error ex)
    	{
    		cout<<ex.what()<<endl;
    		return 0;
    	}
    	end = clock();
    	cout<<"第"<<k<<"个元素"<<res<<endl;
    	cout<<"验证!"<<endl;
    	sort(vec.begin(),vec.end());
    	cout<<"第"<<k<<"个元素"<<vec[k-1]<<endl;
    	cout <<"程序执行时间(单位:毫秒): "<< end-start <<endl;
    	return 0;
    }

  • 相关阅读:
    发送短信/邮件/打电话 code(转)
    如何学习算法
    堆和栈的区别
    2010 baidu笔试
    关于TableView中图片的延时加载(转)
    sqlite + UITableView 实现iPhone大数据浏览
    2010 Google中国笔试试题
    海量数据处理方法总结(转)
    IPhone WebApp 设计开发工具与资源(转)
    DynamicDataSet
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7068132.html
Copyright © 2011-2022 走看看