zoukankan      html  css  js  c++  java
  • LeetCode Array Easy 414. Third Maximum Number

     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.

     问题描述,给定要给非空数组,找出第三大的数,如果找不到则返回最大值。

    思路:用三个数分别存最大 第二 第三大的值。但是由于数组中会出现int的最小边界值。所以干脆用long类型来存储前三个值。

    public int ThirdMax(int[] nums) {
            long max = long.MinValue;
            long sec = long.MinValue;
            long third = long.MinValue;
            
            for(int i = 0; i < nums.Length; i++){
                int temp = nums[i];
                if(temp > max){
                   third = sec;
                    sec = max;
                    max=temp;
                }
                else if(temp < max && temp >sec){
                    third = sec;
                    sec=temp;
                }
                else if(temp < sec && temp >=third){
                    third = temp;
                }
                    
            }
            return third > long.MinValue ? (int)third : (int)max;
        }

  • 相关阅读:
    Linux centos 6.4安装
    vm虚拟机安装,配置与使用
    Linux简介
    360兼容视图
    补丁patch 漏洞 bug或glitch
    迫不得已! ! 仅仅针对IE浏览器的样式,尤其是IE8及以下
    JS延时器 定时器 暂停器 中断器
    CSS动态定位
    一个标准的AJAX请求
    ajax的两个重要参数contentType 和dataType
  • 原文地址:https://www.cnblogs.com/c-supreme/p/9600461.html
Copyright © 2011-2022 走看看