• 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;
        }
    }
    
  • 相关阅读:
    HDU 5861 Road (线段树)
    HDU 5857 Median (推导)
    HDU 5858 Hard problem (数学推导)
    HDU 5867 Water problem (模拟)
    UVALive 7455 Linear Ecosystem (高斯消元)
    A bug about RecipientEditTextView
    当Activity出现Exception时是如何处理的?
    FontSize sp 和 dp 的区别
    Android的Overlay机制
    关于控件问题的分析
  • 原文地址:https://www.cnblogs.com/duyue6002/p/7227908.html
Copyright © 2020-2023  润新知