博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
(leetcode题解)Third Maximum Number
阅读量:4586 次
发布时间:2019-06-09

本文共 1291 字,大约阅读时间需要 4 分钟。

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: 1Explanation: The third maximum is 1.

 

Example 2:

Input: [1, 2]Output: 2Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

 

Example 3:

Input: [2, 2, 3, 1]Output: 1Explanation: Note that the third maximum here means the third maximum distinct number.Both numbers with value 2 are both considered as second maximum. 题意寻找一个数组中第三大的数,如果不存在返回最大的数。 直接的做法就是排序,查找第三个即可,C++实现如下
int thirdMax(vector
& nums) { sort(nums.begin(),nums.end()); int count=1; for(int i=nums.size()-1;i>0;i--) { if(nums[i]!=nums[i-1]) count++; if(count==3) return nums[--i]; } return nums[nums.size()-1]; }

 也可以利用set集合的有序性和唯一性,C++实现如下

int thirdMax(vector
& nums) { set
t_set; for(auto &i:nums) t_set.insert(i); auto r_iter=t_set.rbegin(); if(t_set.size()<3) return *r_iter; r_iter++; r_iter++; return *r_iter; }

 

 

转载于:https://www.cnblogs.com/kiplove/p/6986188.html

你可能感兴趣的文章
FREESWITCH 填坑指南
查看>>
ASP Err.Number 对应的Description
查看>>
Java基础
查看>>
归并排序
查看>>
md5加密通过URL传给后台
查看>>
白化(预处理步骤)【转】
查看>>
eclipse常见问题汇总
查看>>
Vue中点击按钮回到顶部(滚动效果)
查看>>
表单元素
查看>>
eclipse安装activiti工作流插件
查看>>
java容器类:HashMap
查看>>
codeforces793 B. Igor and his way to work (dfs)
查看>>
终端不识别手机设备解决方案
查看>>
Python学习笔记
查看>>
Django 【字段查询谓词表】
查看>>
XenServer修改DNS
查看>>
.Net开发工程师笔试试题
查看>>
POJ 1579 (DP)
查看>>
Android深度探索心得<10>
查看>>
Postman入门
查看>>