zoukankan      html  css  js  c++  java
  • LeetCode_414. Third Maximum Number

    414. Third Maximum Number

    Easy

    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).

    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.
    package leetcode.easy;
    
    public class ThirdMaximumNumber {
    	@org.junit.Test
    	public void test() {
    		int[] nums1 = { 3, 2, 1 };
    		int[] nums2 = { 1, 2 };
    		int[] nums3 = { 2, 2, 3, 1 };
    		System.out.println(thirdMax(nums1));
    		System.out.println(thirdMax(nums2));
    		System.out.println(thirdMax(nums3));
    	}
    
    	public int thirdMax(int[] nums) {
    		int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;
    		boolean minPresent = false;
    		for (int n : nums) {
    			if (n == Integer.MIN_VALUE) {
    				minPresent = true;
    			}
    
    			if (n > max1) {
    				max3 = max2;
    				max2 = max1;
    				max1 = n;
    			} else if (n > max2 && n < max1) {
    				max3 = max2;
    				max2 = n;
    			} else if (n > max3 && n < max2) {
    				max3 = n;
    			}
    
    		}
    		if (max3 != Integer.MIN_VALUE) {
    			return max3;
    		} else {
    			if (minPresent && max2 != Integer.MIN_VALUE) {
    				return max3;
    			} else {
    				return max1;
    			}
    		}
    	}
    }
    
  • 相关阅读:
    vue基础知识
    制作离线yum源
    mysql字符集
    confluence 容器版 搭建部署
    iptables和ipvs
    http状态码
    运维相关网站博客集合
    搭建nexus私有maven私服
    MySQL 常见错误代码说明
    nc(瑞士军刀)
  • 原文地址:https://www.cnblogs.com/denggelin/p/11935413.html
Copyright © 2011-2022 走看看