---
title: "算法基础之寻找第二大的数"
author: "aaron-han"
date: "2012-03-29T15:33:49Z"
tags: []
categories: ["互联网"]
slug: "untitled"
draft: false
lastmod: "2012-03-29T15:37:19Z"
id: 1468948
url: "https://aaron-han.iteye.com/blog/1468948"
---

仅适用于规模N较小的情况。
大致思路：遍历一遍，不断更新max和secondMax。
需要注意两点：1.元素个数小于两个(这个有点打酱油。。)  2.所有元素值相同
代码如下：

```java

import java.util.Arrays;

/**
 * 寻找第二大的数：规模N较小的情况
 * 
 * @author aaron-han
 * 
 */
public class FindSecondMax {

	public static void main(String[] args) {
		int[] arr = com.utils.Utils.randomIntArray();
		System.out.println(Arrays.toString(arr));
		findSecondMax(arr);
	}

	public static void findSecondMax(int[] arr) {
		int length = arr.length;
		if (length < 2) {
			System.out.println("Usage: at least two numbers in array.");
			System.exit(-1);
		}
		int max = arr[0];
		int secondMax = Integer.MIN_VALUE;
		for (int i = 1; i < arr.length; i++) {
			if (arr[i] > max) {
				secondMax = max;
				max = arr[i];
			} else if (arr[i] > secondMax && arr[i] < max) {
				secondMax = arr[i];
			}
		}
		if (secondMax == Integer.MIN_VALUE) {
			System.out.println("No secondMax Number.");
		} else {
			System.out.println("The secondMax = " + secondMax);
		}
	}

}

```


对于N较大的情况，目前的想法是直接快排，然后取index为1的。 :evil: 
欢迎大家指点更好的思路，后边有想法了我会写上来。