-
Notifications
You must be signed in to change notification settings - Fork 0
/
Kth Largest Element in an Array.cpp
68 lines (66 loc) · 1.36 KB
/
Kth Largest Element in an Array.cpp
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
59
60
61
62
63
64
65
66
67
68
#include<iostream>
#include<string>
#include<vector>
#include <cctype>
#include<algorithm>
#include<math.h>
using namespace std ;
typedef struct ListNode{
int val;
ListNode * next;
} ListNode;
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int size = nums.size();
int res, temp;
if(!size)
return 0;
if(k > (size/2)){
k=size-k+1;
for(int i=0;i<k;i++){
res = nums[0];
auto foo = nums.begin();
for(auto iter=nums.begin(); iter!=nums.end(); iter++){
if(*iter < res){
foo = iter;
res = *iter;
}
}
nums.erase(foo);
}
}
else{
for(int i = 0; i < k; i++){
res = nums[0];
auto foo = nums.begin();
for(auto iter = nums.begin(); iter != nums.end(); iter++){
if(*iter > res){
foo = iter;
res = *iter;
}
}
nums.erase(foo);
}
}
return res;
}
void print()
{
int X[]={3,2,1,4,6,5};
vector<int> A(X,X+6);
//cout<<findKthLargest(A,0)<<endl;
//cout<<findKthLargest(A,1)<<endl;
cout<<findKthLargest(A,1)<<endl;
//cout<<findKthLargest(A,3)<<endl;
//cout<<findKthLargest(A,4)<<endl;
}
};
int main()
{
Solution test;
// cout<<test.Low("A man, a plan, a canal: Panama")<<endl;
test.print();
// cout<<atoi("2147483648")<<endl;
system("pause");
}