Second Max of Array
Find the second max number in a given array.
Example
Given [1, 3, 2, 4], return 3.
Given [1, 2], return 1.
Note
You can assume the array contains at least two numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public class Solution { /** * @param nums: An integer array. * @return: The second max number in the array. */ public int secondMax(int[] nums) { /* your code */ int max = Math.max(nums[0], nums[1]); int secondMax = Math.min(nums[0], nums[1]); for (int i = 2; i < nums.length; i++) { if (nums[i] > max) { secondMax = max; max = nums[i]; } else { if (nums[i] > secondMax) { secondMax = nums[i]; } } } return secondMax; } } |