网站优化快照,云岭建设集团的网站,怎样注册wordpress,手机网站开发 视频给定一个非空数组#xff0c;返回此数组中第三大的数。如果不存在#xff0c;则返回数组中最大的数。要求算法时间复杂度必须是O(n)。
示例 1:
输入: [3, 2, 1]
输出: 1
解释: 第三大的数是 1. 示例 2:
输入: [1, 2]
输出: 2
解释: 第三大的数不存在, 所以返回最大的数…给定一个非空数组返回此数组中第三大的数。如果不存在则返回数组中最大的数。要求算法时间复杂度必须是O(n)。
示例 1:
输入: [3, 2, 1]
输出: 1
解释: 第三大的数是 1. 示例 2:
输入: [1, 2]
输出: 2
解释: 第三大的数不存在, 所以返回最大的数 2 . 示例 3:
输入: [2, 2, 3, 1]
输出: 1
解释: 注意要求返回第三大的数是指第三大且唯一出现的数。 存在两个值为2的数它们都排第二。
思路1见代码分情况即可。记得特殊处理第三小正好是Integer.MIN_VALUE的情况。
class Solution {public int thirdMax(int[] nums) {int firstInteger.MIN_VALUE;int secondInteger.MIN_VALUE;int thirdInteger.MIN_VALUE;int sum0;boolean boolfalse;for(int i:nums){if(iInteger.MIN_VALUE)booltrue;if(ifirst || isecond || ithird)continue;if(ifirst){thirdsecond;secondfirst;firsti;sum;}else if(isecond){thirdsecond;secondi;sum;}else if(ithird){thirdi;sum;}}if(sum2){return third;}else if(sum2 bool){return third;}else{return first;}}
}