作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/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.

题目大意

找出一个数组中第三大的数字,如果不存在的话,就返回最大数字。

解题方法

替换最大值数组

最基本的方法,找到最大值,然后每次把最大值移除,这样重复三次就得到了第三大的值。

class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def setMax(nums):
_max = max(nums)
for i, num in enumerate(nums):
if num == _max:
nums[i] = float('-inf')
return _max
max1 = setMax(nums)
max2 = setMax(nums)
max3 = setMax(nums)
return max3 if max3 != float('-inf') else max(max1, max2)

使用set

用set去算,set的时间复杂度是O(n)。set的remove()方法可以去除某个值,不过每次只能去除一个。

class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums_set = set(nums)
if len(nums_set) < 3:
return max(nums_set)
nums_set.remove(max(nums_set))
nums_set.remove(max(nums_set))
_max = max(nums_set)
return _max

这个方法的C++版本如下:

class Solution {
public:
int thirdMax(vector<int>& nums) {
set<int> s;
for (int num : nums) {
s.insert(num);
}
if (s.size() < 3) {
return maxset(s);
}
s.erase(maxset(s));
s.erase(maxset(s));
return maxset(s);
}
private:
int maxset(set<int> &s) {
int res = INT_MIN;
for (int c : s) {
res = max(res, c);
}
return res;
}
};

原来C++也有求最大值函数叫做max_element(),参数是起始和结束位置,返回的是指针。

class Solution {
public:
int thirdMax(vector<int>& nums) {
set<int> s;
for (int num : nums) {
s.insert(num);
}
if (s.size() < 3) return *max_element(s.begin(), s.end());
s.erase(*max_element(s.begin(), s.end()));
s.erase(*max_element(s.begin(), s.end()));
return *max_element(s.begin(), s.end());
}
};

三个变量

维护三个变量分别保存最大、次大、第三大的值,只需要遍历一次数组,找到这个数字和三个变量的大小关系,就能对应的更新对应的值。

为了去重,elif里面写了当前的Num要处于开区间内。

class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# s1 > s2 > s3
s1, s2, s3 = float('-inf'), float('-inf'), float('-inf')
for num in nums:
if num > s1:
s1, s2, s3 = num, s1, s2
elif num < s1 and num > s2:
s2, s3 = num, s2
elif num < s2 and num > s3:
s3 = num
return s3 if s3 != float('-inf') else s1

这个方法的C++写法如下,为什么需要使用long long 呢?因为当第三大的数字是INT_MIN的话,你如果把三个数字都初始化成了INT_MIN就没法判断了。

class Solution {
public:
int thirdMax(vector<int>& nums) {
long long s1, s2, s3;
s1 = s2 = s3 = LLONG_MIN;
for (int num : nums) {
if (num > s1) {
s3 = s2;
s2 = s1;
s1 = num;
} else if (num < s1 && num > s2) {
s3 = s2;
s2 = num;
} else if (num < s2 && num > s3) {
s3 = num;
}
}
return s3 != LLONG_MIN ? s3 : s1;
}
};

日期

2018 年 2 月 4 日
2018 年 11 月 27 日 —— 最近的雾霾太可怕

【LeetCode】414. Third Maximum Number 解题报告(Python & C++)的更多相关文章

  1. 【LeetCode】306. Additive Number 解题报告(Python)

    [LeetCode]306. Additive Number 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http: ...

  2. C#版 - Leetcode 414. Third Maximum Number题解

    版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...

  3. LeetCode 414. Third Maximum Number (第三大的数)

    Given a non-empty array of integers, return the third maximum number in this array. If it does not e ...

  4. LeetCode 414 Third Maximum Number

    Problem: Given a non-empty array of integers, return the third maximum number in this array. If it d ...

  5. 【LeetCode】263. Ugly Number 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 除去2,3,5因子 日期 [LeetCode] 题目 ...

  6. 【LeetCode】136. Single Number 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 异或 字典 日期 [LeetCode] 题目地址:h ...

  7. 【LeetCode】507. Perfect Number 解题报告(Python & Java & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  8. 【LeetCode】 202. Happy Number 解题报告(Java & Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 迭代 日期 [LeetCode] 题目地址:h ...

  9. 【LeetCode】268. Missing Number 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 求和 异或 日期 题目地址:https://leet ...

随机推荐

  1. 57-Palindrome Linked List

    Palindrome Linked List My Submissions QuestionEditorial Solution Total Accepted: 46990 Total Submiss ...

  2. 中兴交换机基础配置(备份、dhcp中继、monitor)

    1. 备份配置 格式: copy tftp/sftp/ftp [vrf mng] root: 本地文件 远端文件 1. 通过tftp进行备份,vrf mng表示指定使用管理口链路连接 copy tft ...

  3. 从 ClickHouse 到 ByteHouse:实时数据分析场景下的优化实践

    本文来自火山引擎公众号,原文发布于2021-09-06. 近日,字节跳动旗下的企业级技术服务平台火山引擎正式对外发布「ByteHouse」,作为 ClickHouse 企业版,解决开源技术上手难 &a ...

  4. opencv学习(三)——绘图功能

    绘图功能 我们将学习以下函数:cv.line(),cv.circle(),cv.rectangle(),cv.ellipse(),cv.putText()等. 在这些功能中,有一些相同的参数: img ...

  5. 【♪♪♪】网易云音乐mp3真实地址

    参考别人的博客,得到下面的地址,填上ID号即可,后缀的[.mp3]不用输入 http://music.163.com/song/media/outer/url?id= 例如 最终,合并地址为 http ...

  6. 100个Shell脚本——【脚本7】批量建立用户

    [脚本7]批量建立用户 编写shell脚本,批量建立用户user_00, user_01, ... user_100并且所有用户同属于users组. 一.脚本 #!/bin/bash group=`c ...

  7. Linux基础命令---ntpdate网络时间服务器

    ntpdate ntpdate指令通过轮询指定为服务器参数的网络时间协议(NTP)服务器来设置本地日期和时间,从而确定正确的时间. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS ...

  8. django搭建示例-ubantu环境

    python3安装--------------------------------------------------------------------------- 最新的django依赖pyth ...

  9. APiCloud - api对象

    详见网址:https://www.cnblogs.com/jiqing9006/p/5919317.html

  10. 『学了就忘』Linux启动引导与修复 — 74、Linux系统的修复模式(光盘修复模式)

    目录 1.光盘修复模式概念 2.光盘修复模式修复系统问题 (1)准备系统光盘 (2)进入BIOS (3)修改BIOS的启动顺序 (4)进入光盘修复模式 (5)修复系统 (6)修复系统实操 (7)总结 ...