479. Second Max of Array【easy】
2024-10-19 13:22:41
Find the second max number in a given array.
Notice
You can assume the array contains at least two numbers.
Example
Given [1, 3, 2, 4]
, return 3
.
Given [1, 2]
, return 1
.
解法一:
public class Solution {
/**
* @param nums: An integer array.
* @return: The second max number in the array.
*/
public int secondMax(int[] nums) {
int first = Math.max(nums[0], nums[1]);
int second = Math.min(nums[0], nums[1]); for (int i = 2; i < nums.length; i++) {
if (nums[i] > first) {
second = first;
first = nums[i];
} else if (nums[i] > second) {
second = nums[i];
}
}
return second;
}
}
从数组前两位找到first大和second大的,从i=2开始遍历,不断找当前first大和second大。
最新文章
- php使用post方式获得文件扩展名
- 1.Java基础之System对象
- C# Enum Name String Description之间的相互转换
- Logging configuration
- PHP开发环境配置
- jsp页面不能使用EL表达式
- matlab 怎么保存plot的图 到指定文件夹
- leetcode-WordLadder
- [Swift]LeetCode423. 从英文中重建数字 | Reconstruct Original Digits from English
- c++ cout、cin、endl
- scrapy框架原理学习
- 依赖注入容器之Castle Windsor
- python 穷举法 算24点(史上最简短代码)
- Latex中如何设置字体颜色(3种方式)
- python 中dir()和__dict__的区别
- 获取Spring项目配置文件元素
- 【转】iOS - SQLite 数据库存储
- LOJ P3960 列队 树状数组 vector
- 记录一次teamview无法远程连接对方teamview的过程
- 此时本机的BootLoader程序坏了,也就是说grub第一阶段坏掉了,该如何修复