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.
思路:找出一个数组中第三大的元素,这里只是说integer,没有规定范围,因此应该考虑到int型的最大值和最小值,INT_MIN,INT_MAX,
自己的想法:(129ms)比较简单,使用额外的辅助空间,将不重复的元素排序
 int thirdMax(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<int> ans;
int i;
for(i=nums.size()-;i>=;--i)
{
if(find(ans.begin(),ans.end(),nums[i])==ans.end())//一开始自己的想法是进行排序,然后相邻元素是否相等,
ans.push_back(nums[i]);
}
if(ans.size()<)
return ans[];
return ans[];
}

或者这样:

优秀代码:(6ms)既然要找出第三大的元素值,则首先设定三个最小值,然后遍历所有的元素,找出前三大的元素值

 int thirdMax(vector<int>& nums) {
long long a, b, c;
a = b = c = LONG_MIN ;
for(auto num : nums){
if(num <= c || num ==b || num == a)
continue;
else
c = num;
if(c > b)
swap(b, c);
if(b > a)
swap(a, b);
}
return c == LONG_MIN ? a : c;
}

函数set下的代码:

 int thirdMax(vector<int>& nums) {
set<int> top;
for (auto i : nums) {
top.insert(i);
if (top.size() > ) top.erase(top.begin());
}
return top.size() == ? *top.begin() : *top.rbegin();
}

set参考链接:http://www.cnblogs.com/BeyondAnyTime/archive/2012/08/13/2636375.html

最新文章

  1. [v9] 列表页 调用 正文内容 或 自定义 字段(moreinfo的调用方法)
  2. 使用percona-toolkit校验主从数据的一致性
  3. [转]Could not load file or assembly &#39;System.Core, Version=2.0.5.0 和autofac冲突的问题
  4. ASP.NET四则运算--工厂模式
  5. 常用的JavaScript验证正则表达式1
  6. 在Ubuntu下ADT识别不出真机的解决办法
  7. VC2010编译错误
  8. linux内核Makefile整体分析
  9. 网络基础Cisco路由交换一
  10. echarts-五分钟的教程
  11. 汇编语言--微机CPU的指令系统(五)(字符串操作指令)
  12. SQL Server-索引故事的遥远由来,原来是这样的?(二十八)
  13. 找到IIS 站点对应的站点日志
  14. java ssl https 连接详解 生成证书 tomcat keystone
  15. 20175209 实验三《敏捷开发与XP实践》实验报告
  16. WSAAsyncSelect 模型
  17. /proc文件夹介绍
  18. Redis总结(五)缓存雪崩和缓存穿透等问题(转载)
  19. jdk1.8新特性-Lambda表达式使用要点
  20. Django web框架之权限管理一

热门文章

  1. js 实时监听textarea输入
  2. SpringCloud学习笔记《---04 Hystrix---》基础篇
  3. Python遇到的第一个问题
  4. JVM的内存空间
  5. echarts高级
  6. LintCode_1 单例模式
  7. div 和 span 标记
  8. SpringMVC处理请求的大致流程是怎么样的
  9. 编写函数处理user_list,新方法
  10. Appscan standard怎么设置外部浏览器为IE