414. Third Maximum Number (java)
来源:互联网 发布:java nio网络编程 编辑:程序博客网 时间:2024/05/01 02:31
414. Third Maximum Number
DescriptionSubmissionsSolutions
- Total Accepted: 27406
- Total Submissions: 100537
- Difficulty: Easy
- Contributors: ZengRed, 1337c0d3r
Given a non-empty array of integers, return the third maximuhttps://leetcode.com/problems/third-maximum-number/#/descriptionm 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: 1Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]Output: 2Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]Output: 1Explanation: Note that the third maximum here means the third maximum distinct number.Both numbers with value 2 are both considered as second maximum.
题目链接:https://leetcode.com/problems/third-maximum-number/#/description
解题思路:三次遍历,第一次找出最大值,第二次找出第二大的值,第三次找出第三大的值。三个值要初始化为最小值,也就是Integer.MIN_VALUE,但给定的数组会有这个最小值,因此不能根据是第三大的值否等于初始值来判断是否找到第三大的值,加一个布尔标记就好。
代码如下:
public class Solution { public int thirdMax(int[] nums) { int max = Integer.MIN_VALUE; int m2 = Integer.MIN_VALUE; int m3 = Integer.MIN_VALUE; boolean flog = false; 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] > m2){ m2 = nums[i]; } } for(int i=0;i<nums.length;i++){ if(nums[i] < m2 && nums[i] >= m3){ m3 = nums[i]; flog = true; } } if(flog){ return m3; }else{ return max; } }}
0 0
- 414. Third Maximum Number (java)
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number*
- 414. Third Maximum Number
- 死磕 Java 并发 : 深入分析 volatile 的实现原理
- 计算机专外Week2-Exercises
- ubuntu下python 2.7与python 3.X的转换
- python把函数作为参数
- 网络编程基础
- 414. Third Maximum Number (java)
- Floyd—Warshall算法
- 问题:Hibernate ,测试类中并没有在控制台打印出sql语句?
- Simple game 【概率期望】
- 菜鸟程序员的超神之路
- WebView:后退按钮的作用,替换成WebView里的查看历史页面
- 命令行编译源文件
- win7部分便笺的元数据已被损坏
- qt5.7.0creator打不开解决办法