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;
        }
    }
    
  • 相关阅读:
    分布式事务之可靠消息
    分布式事务之本地消息表
    分布式事务
    数据库之 事务
    WePY开发小程序(二):项目入口及注册页面、组件
    WePY开发小程序(一):入门
    vue学习笔记-事件监听
    vue学习笔记-列表渲染
    vue学习笔记-缩写
    vue学习笔记-常用指令
  • 原文地址:https://www.cnblogs.com/duyue6002/p/7227908.html
Copyright © 2011-2022 走看看