zoukankan      html  css  js  c++  java
  • LeetCode & Q414-Third Maximum Number-Easy

    Array Math

    Description:

    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.
    

    刚开始不会写,想先排序再找,发现超级麻烦,就放弃了,看了Discuss,直接用数学的方法来比较大小就好,我感觉我永远都get不到题目想让我怎么解....

    public class Solution {
        public int thirdMax(int[] nums) {
            Integer num1 = null;
            Integer num2 = null;
            Integer num3 = null;
            
            for (Integer num : nums) {
                if (num.equals(num1) || num.equals(num2) || num.equals(num3)) continue;
                if (num1 == null || num > num1) {
                    num3 = num2;
                    num2 = num1;
                    num1 = num;
                } else if (num2 == null || num > num2) {
                    num3 = num2;
                    num2 = num;
                } else if (num3 == null || num > num3) {
                    num3 = num;
                }
            }
            
            return num3 == null ? num1 : num3;
        }
    }
    
  • 相关阅读:
    Apache的Thrift引发的编译思考
    QQ的小秘密
    快速简化Android截屏工作
    Solution of wireless link "PCI unknown" on Centos 7.1
    Java Date Compare
    eclipse集成tomcat日志文件输出配置
    身份证号码验证正则表达式
    curl用法一例 传递代理用户名密码
    HTML 5 placeHolder
    JavaScript(ECMAScript) with 语句
  • 原文地址:https://www.cnblogs.com/duyue6002/p/7227908.html
Copyright © 2011-2022 走看看