1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #include <iostream> #include <vector> #include <algorithm>
using namespace std;
int partition(vector<int>& nums, int low, int high) { int pivot = nums[high]; int i = low - 1; for (int j = low; j < high; ++j) { if (nums[j] > pivot) { ++i; swap(nums[i], nums[j]); } } swap(nums[i + 1], nums[high]); return i + 1; }
int findKthLargest(vector<int>& nums, int k, int low, int high) { if (low <= high) { int pi = partition(nums, low, high); if (pi == k - 1) { return nums[pi]; } else if (pi > k - 1) { return findKthLargest(nums, k, low, pi - 1); } else { return findKthLargest(nums, k, pi + 1, high); } } return -1; }
int findSecondLargest(vector<int>& nums) { int n = nums.size(); return findKthLargest(nums, 2, 0, n - 1); }
int main() { vector<int> nums = {3, 2, 1, 5, 6, 4}; int secondLargest = findSecondLargest(nums); cout << "The second largest number is: " << secondLargest << endl; return 0; }
|