题意:求数组中第三大的数,重复的数不算
思路:用三个变量记录第一大,第二大,第三大的数,在遍历数据过程中更新这三个值。
具体代码如下:
public class Solution
{
public int thirdMax(int[] nums)
{
long first, second, third;
first = second = third = Long.MIN_VALUE;
for (int num : nums)
{
if (num == first || num == second || num == third) continue;
if (num > first)
{
third = second;
second = first;
first = num;
}
else if (num > second)
{
third = second;
second = num;
}
else if (num > third) third = num;
}
return (third == Long.MIN_VALUE) ? (int)first : (int)third;
}
}