414. Third Maximum Number (java)

414. Third Maximum Number

  • 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: 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.

题目链接: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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值