zoukankan      html  css  js  c++  java
  • [置顶] 从一位数组中提取最小k个元素

    #include <iostream>
    #include <cstdlib>
    #include <vector>
    
    using namespace std;
    /*
     * 从n个整型数组中提取前k个最小整数
     * 方法一:利用快速排序进行递归划分
    */
    const int Max = 100;   // 数组最大容量
    class Solution {
    private:
    	vector<int>array;  // 输入的数组 
    	vector<int>kmin;   // 提取的k个最小值的数组
        /*   
    	 * 对数组进行划分,返回“中值”位置
    	*/
    	int Adjust(vector<int>&arr, int low, int high) {
    		int i, j;
    		i = low;
    		j = high;
    		int tmp = arr[low];
    		while(i < j) {
    			while(i < j && arr[j] > tmp) j--;
    			if(i < j) arr[i++] = arr[j];
    
    			while(i < j && arr[i] < tmp) i++;
    			if(i < j) arr[j--] = arr[i];
    
    		}
    		arr[i] = tmp;
    		return i;
    	}
        /*
    	 * 利用上面的调整函数进行查找
    	*/
    	void JustDoIt(vector<int>&arr, int low, int high, int k) {
    		int i;
    		int mid = Adjust(arr, low, high);
    		static bool find;     // 用于递归截断
    		/*
    		 * 找到解
    		*/
    		if(!find && (mid + 1 == k || mid == k)) {
    			find = true;
    			for(i = 0;i < k;i++) {
    				kmin.push_back(arr[i]);
    			}
    			return;
    		}
    		/*
    		 * 递归处理 
    		*/
    		else if(!find && k > mid + 1) {
    			JustDoIt(arr, mid + 1, high, k);
    		}
    		else if(!find) {
    			JustDoIt(arr, low, mid - 1, k);
    		}
    	}
    
    public:
    	Solution(int n) {
    		if(n < 0 || n>= Max) {
    			cerr<<"参数不合法!"<<endl;
    			exit(1);
    		}
    		int i;
    		int e;
    		for(i = 0;i < n;i++) {
    			cout<<"请输入第"<<i<<"个整数:";
    			cin>>e;
    			if(!cin.good()) exit(1);
    			array.push_back(e);
    		}
    	}
    	void JustDoIt(int k) {
    		if(k <= 0 || k > array.size()) {
    			cerr<<"参数不合法!"<<endl;
    			exit(1);
    		}
    		JustDoIt(array, 0, array.size() - 1, k);
    	}
    	void show()  {
    		vector<int>::iterator it;
    		for(it = kmin.begin(); it != kmin.end(); it++) {
    			cout<<*it<<endl;
    		}
    	}
    };
    
    void main() {
    	Solution s(10);
    	s.JustDoIt(3);
    	s.show();
    }



  • 相关阅读:
    django2.0+连接mysql数据库迁移时候报错
    微信小程序路由跳转
    洛谷P3144 [USACO16OPEN]关闭农场Closing the Farm
    洛谷P3143 [USACO16OPEN]钻石收藏家Diamond Collector
    洛谷P2677 超级书架 2
    洛谷P2676 超级书架
    洛谷P3146 [USACO16OPEN]248
    洛谷P1396 营救
    洛谷P1772 [ZJOI2006]物流运输
    P3102 [USACO14FEB]秘密代码Secret Code
  • 原文地址:https://www.cnblogs.com/bbsno1/p/3279702.html
Copyright © 2011-2022 走看看