废话不多说 直接上题目:
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1.
Example 2:
Input: [1, 2] Output: 2 Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1] Output: 1 Explanation: Note that the third maximum here means the third maximum distinct number. Both numbers with value 2 are both considered as second maximum.
简单来说,就是给你一个非空,无序,有重复项的整数数组,返回这个数组中第三大的数字,如果数组中的数字数目小于三个的话,则返回数组中的最大值
解题思路:
这道题看起来并不是太难,个人认为主要考点有:如何对数组排序,如何处理数组中重复项
我的算法:
1:首先将数组进行排序,运用Array.sort
2:处理数组中重复项,处理重复项的算法就是运用两个指针,两个指针龟兔赛跑,指针龟是慢指针,兔子是快指针,兔子指针会遍历一遍数组,如果龟指针所对应的数字与兔子指针不同的时候,龟指针才会向前移,如果龟指针与兔子指针对应的数字相同的时候,证明我们遇到了重复项。我们只需要记录龟指针所经历的所有数字就避免了所有重复项。遍历整个数组之后,我们龟指针指向的就是新数组的最后一项
3:得到了新的无重复项的数组,我们判断数组长度,小于3,则返回新数组最后一项,如果大于3,则返回倒数第三个数字。
代码如下:
public int thirdMax(int[] nums) {
Arrays.sort(nums);
int walker = 0;
for (int runner = 0 ; runner < nums.length; runner ++){
if(nums[walker] != nums[runner]){
walker ++ ;
nums[walker] = nums[runner];
}
}
if (walker < 2) {
return nums[walker];
}
else{
return nums[walker - 2];
}
}
运算速度分析:
我们运用了Arrays.sort,Array.sort 运用的是quicksort,O(nlogn),我们还运用了遍历,O(n),所以综合下来,我们O(nlogn)