- 1 public int thirdMax(int[] nums) {
- 2 int max,
- mid,
- small,
- count;
- 3 max = mid = small = Integer.MIN_VALUE;
- 4 count = 0; //Count how many top elements have been found.
- 5 6
- for (int x: nums) {
- 7 //Skip loop if max or mid elements are duplicate. The purpose is for avoiding right shift.
- 8
- if (x == max || x == mid) {
- 9
- continue;
- 10
- }
- 11 12
- if (x > max) {
- 13 //right shift
- 14 small = mid;
- 15 mid = max;
- 16 17 max = x;
- 18 count++;
- 19
- } else if (x > mid) {
- 20 //right shift
- 21 small = mid;
- 22 23 mid = x;
- 24 count++;
- 25
- } else if (x >= small) { //if small duplicated, that's find, there's no shift and need to increase count.
- 26 small = x;
- 27 count++;
- 28
- }
- 29
- }
- 30 31 //"count" is used for checking whether found top 3 maximum elements.
- 32
- if (count >= 3) {
- 33
- return small;
- 34
- } else {
- 35
- return max;
- 36
- }
- 37
- }
来源: http://www.bubuko.com/infodetail-1857771.html