先看题目要求
①找出数组中第三大的数②要求算法的时间复杂度为O(n)
解决思路 要求算法的时间复杂度为O(n) 则先对数组进行排序,再取对应位置下标的思路是不可取的
我采用的是每次都找当前数组最大值的方法,然后在下一轮循环中,将寻找到的最大值跳过。最终找到问题的解。
代码:
class Solution {
public int thirdMax(int[] nums) {
int max = Math.negateExact((int)Math.pow(2, 31))-1;
int secMax = Math.negateExact((int)Math.pow(2, 31))-1;
int thiMax = Math.negateExact((int)Math.pow(2, 31))-1;
boolean flag = true;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] != max && nums[i] >=secMax) {
secMax = nums[i];
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] != max && nums[i] != secMax && nums[i] >= thiMax) {
flag = false;
thiMax = nums[i];
}
}
if (flag) {
return max;
}
return thiMax;
}
}