Loading content...
Created On: December 2, 2023
class Solution{
public:
int findSecondLargest(vector<int> nums){
int largest = INT_MIN;
int second_largest = largest;
for(auto x: nums){
if(x > largest){
second_largest = largest;
largest = x;
}
if(x > second_largest && x < largest)
second_largest = x;
}
if(second_largest == INT_MIN)
return -1;
else
return second_largest;
}
};By using the same approach we can find the second smallest element also .
class Solution{
public:
int findSecondSmallest(vector<int> nums){
int smallest = INT_MAX;
int second_smallest = smallest;
for(auto x: nums){
if(x < smallest){
second_smallest = smallest;
smallest = x;
}
if(x < second_smallest && x > smallest)
second_smallest = x;
}
if(second_smallest == INT_MAX)
return -1;
else
return second_smallest;
}
};