Advertisement
Guest User

Untitled

a guest
Feb 12th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <vector>
  4. #include <stdlib.h>
  5.  
  6. using namespace std;
  7.  
  8. class Solution {
  9. public:
  10.     void swap(int &x, int &y){
  11.         int temp = x;
  12.         x = y;
  13.         y = temp;
  14.     }
  15.  
  16.     int findIdx(vector<int>& nums, int root, int idx){
  17.  
  18.     int i = -1, j = nums.size();
  19.  
  20.         while (true){
  21.  
  22.         do{
  23.             ++i;
  24.         }while(nums[i] < root);
  25.  
  26.         do{
  27.             --j;
  28.         }while(nums[j] > root);
  29.  
  30.         if (i < j){
  31.             swap(nums[i], nums[j]);
  32.         }else return j;
  33.     }
  34.  
  35.         return 0;
  36.     }
  37.  
  38.     int findKthLargest(vector<int>& nums, int k) {
  39.     cout << "******";
  40.         for (int i = 0; i< nums.size(); i++)
  41.         cout << nums[i] << "\n";
  42.     cout << "******\n";
  43.     if (nums.size() == 1){
  44.         cout << nums[0] << "\n";
  45.         return nums[0];
  46.     }
  47.  
  48.         int idx = rand() % nums.size();
  49.         int root = nums[idx];
  50.         cout << root << " At " << idx << "\n";
  51.         int new_idx = findIdx(nums, root, idx);
  52.         //int new_idx = nums.size() - idx;
  53.         cout << root << " At " << idx << " " << new_idx << "\n";
  54.  
  55.         if (k-1 < new_idx){
  56.             vector<int> temp (nums.begin(), nums.begin() + new_idx + 1);
  57.             return findKthLargest(temp, k);
  58.         }
  59.         else if (k-1 > new_idx) {
  60.             vector<int> temp (nums.begin() + new_idx + 1, nums.end());
  61.             return findKthLargest(temp, k - new_idx - 1);
  62.         } else {
  63.             return nums[new_idx];
  64.         }
  65.     }
  66. };
  67.  
  68. int main(){
  69.     Solution *sol = new Solution;
  70.     int num[] = {99, 99};
  71.     vector<int> nums(num, num + sizeof(num)/sizeof(int));
  72.     std::cout << sol->findKthLargest(nums, 1);
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement