【Leetcode】414.Third Maximum Number
程序员文章站
2022-03-07 19:45:37
...
题目:
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).
注意:
1.他说是非空的,数组有可能是[1,2]这种情况。
2.时间复杂度是O(n)就不能sort,只能遍历。
3.第一遍写的时候没有看题,他说的是没有第三最大的就返回最大的,所以最后else return返回的是first不是second。
4.我第一遍写的时候是把 first 设置成nums[0],second 和 third 都设置成0,然后在循环里int i = 1 去遍历,后来发现不对,因为如果是[1,2]的情况,相当于最后是[2,1,0]。第三大返回的就是0了。
5.我开始的时候想不明白第二个判断条件,为什么不能等于first,后来终于明白了,会出现这样的结果。
Code:
class Solution {
public int thirdMax(int[] nums) {
int first = nums[0];
int second = nums[0];
int third = nums[0];
for(int i=0;i<nums.length;i++){
if(nums[i]>first){
third = second;
second = first;
first = nums[i];
}else if (nums[i]!=first && (nums[i] > second || second == first)){
third = second;
second = nums[i];
}else if((nums[i]!=first && nums[i] != second) && (nums[i] > third || third == second || third == first)){
third = nums[i];
}
}
if(first>second && second>third) return third;
else return first;
}
}
上一篇: Django的form表单
推荐阅读
-
leetcode 136 Single Number bit Option
-
[leetcode] 306. Additive Number 解题报告
-
LeetCode_#9_回文数 Palindrome Number_C++题解
-
LeetCode------Maximum SubArray
-
leetcode【53】Maximum Subarray
-
【LeetCode】806. Number of Lines To Write String
-
Leetcode 1498. Number of Subsequences That Satisfy the Given Sum Condition (python)
-
LeetCode 1020. Number of Enclaves 解题报告(python)
-
Leetcode 1530. Number of Good Leaf Nodes Pairs (python)
-
Leetcode 200. Number of Islands (python+cpp)