1. 程式人生 > >LeetCode 414. Third Maximum Number

LeetCode 414. Third Maximum Number

一、問題描述

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).

Example1

Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.

Example2

Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example3

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.

二、題意分析

找到第三大的數,如果沒有第三大的數就返回最大的數

三、解題思路

直接對第一,第二,第三大的數分別進行判斷,要注意的是陣列中的數會取到整數的最小值。

程式碼實現

class Solution
{ public int thirdMax(int[] nums) { if(nums.length == 1) return nums[0]; else if(nums.length == 2) return Math.max(nums[0], nums[1]); int max = nums[0]; for(int i = 1; i < nums.length; i++){ max = Math.max(max, nums[i]); }
//arr儲存第一,第二,第三大數 int[] arr = new int[3]; arr[0] = Integer.MIN_VALUE; arr[1] = Integer.MIN_VALUE; arr[2] = max; int counts = 1; boolean flag = false; for(int key : nums){ // 處理整數最小值的情況 if(key == Integer.MIN_VALUE) flag = true; if(key <= arr[0]) continue; // 第二大數 if(key < arr[2] && key > arr[1]){ int tmp = arr[1]; arr[1] = key; arr[0] = tmp; counts++; } // 第三大數 if(key > arr[0] && key < arr[1]){ arr[0] = key; counts++; } } if(counts > 2) return arr[0]; else if(flag && counts == 2) return Integer.MIN_VALUE; return max; } }

時間、空間複雜度分析

  1. 時間複雜度

O (n)

  1. 空間複雜度

O(1)

在這裡插入圖片描述