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
原创粉丝点击