Today is a simple requirement: Find the second largest element in a sequence.
At a glance, I feel that there are many solutions to this problem, because it is not a difficult problem. There are several solutions as you may think:
1. First sort and then take the elements at the second position.
2. traverse the element sequence cyclically, find the largest element, and remove it. Repeat this process to obtain the second largest element.
Of course there are other ideas. I will not list them here. If you have any good ideas, please leave a message for us to discuss it together.
After careful analysis, it is not difficult to find that although the above method can achieve the goal, the efficiency is not high. The first method is equivalent to a sorting process, which can be completed at least at the time of O (nlogn. The second method needs to traverse the sequence twice. Although the time complexity of O (n) + O (n) is not unacceptable, it still needs to loop twice. For those who write software, we obviously hope thatCodeIs "perfect. Therefore, we propose a method that only repeats once for your reference. If you have a good method, please feel free to raise it.
This article introducesAlgorithmIdeas:
Since we can traverse the largest element in a loop, why can't we save the second largest element? Of course, we can, in the case of relatively large elements,As long as you save a small one, after a loop, this element is the second largest element..
The code is simpler.
Int Find_second_biggest (vector < Int > & V ){
Int Len = V. Size ();
Int Max, second;
If (LEN < 2 ){
Return - 1 ;
}
If (V [ 0 ]> V [ 1 ]) {
Second = V [ 1 ];
Max = V [0 ];
}
Else {
Second = V [ 0 ];
Max = V [ 1 ];
}
For ( Int I = 2 ; I <Len; I ++ ){
If (Max <V [I]) {
Second = max;
Max = V [I];
}
Else If (Second <V [I]) {
Second = V [I];
}
}
Return Second;
}
I believe you have read the code. You know more about it. Is it very simple? It only uses one loop. This problem is very simple. The purpose of writing this article is to remind yourself that you should first think about the problem, rather than simply using simple and violent methods, if you think about it for half an hour, it may save a day or even more time.
Of course, this method is not necessarily the best. I hope you can make a lot of bricks.
Postscript: I submitted a version with an error. It can be said that I had learned a lesson and put it up without testing, so that I made a very basic error. It seems that you should try again later. You cannot be too confident. This version is tested and should be a usable version. If you find any data that may cause errors, please try again.