414. Third Maximum Number

来源:互联网 发布:数据采集有哪几种接头 编辑:程序博客网 时间:2024/06/06 23:13

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.

Subscribe to see which companies asked this question.

public class Solution {    public int thirdMax(int[] nums) {        Integer n1 = nums[0], n2 = null, n3 = null;for (int i = 1; i < nums.length; ++i) {int n = nums[i];if (n2 == null || n3 == null) {if (n2 == null) {if (n > n1) {n2 = n1;n1 = n;} else if (n < n1)n2 = n;} else {if (n > n1) {n3 = n2;n2 = n1;n1 = n;} else if (n < n1 && n > n2) {n3 = n2;n2 = n;} else if (n < n2 ) {n3 = n;}}} else {if (n > n1) {n3 = n2;n2 = n1;n1 = n;} else if (n < n1 && n > n2) {n3 = n2;n2 = n;} else if (n < n2 && n > n3) {n3 = n;}}}if (n3 == null)return n1;elsereturn n3;    }}


0 0