| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.ThirdMaximumNumber; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ThirdMaximumNumberLinear : IThirdMaximumNumber |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int ThirdMax(int[] nums) |
| 8 | 24 | | { |
| 8 | 25 | | switch (nums.Length) |
| | 26 | | { |
| | 27 | | case 1: |
| 1 | 28 | | return nums[0]; |
| | 29 | | case 2: |
| 1 | 30 | | return Math.Max(nums[0], nums[1]); |
| | 31 | | } |
| | 32 | |
|
| 18 | 33 | | int? firstMax = null, secondMax = null, thirdMax = null; |
| | 34 | |
|
| 58 | 35 | | foreach (var num in nums) |
| 20 | 36 | | { |
| 20 | 37 | | if (num == firstMax || num == secondMax || num == thirdMax) |
| 3 | 38 | | { |
| 3 | 39 | | continue; |
| | 40 | | } |
| | 41 | |
|
| 17 | 42 | | if (!firstMax.HasValue || num > firstMax) |
| 11 | 43 | | { |
| 11 | 44 | | thirdMax = secondMax; |
| 11 | 45 | | secondMax = firstMax; |
| 11 | 46 | | firstMax = num; |
| 11 | 47 | | } |
| 6 | 48 | | else if (!secondMax.HasValue || num > secondMax) |
| 2 | 49 | | { |
| 2 | 50 | | thirdMax = secondMax; |
| 2 | 51 | | secondMax = num; |
| 2 | 52 | | } |
| 4 | 53 | | else if (!thirdMax.HasValue || num > thirdMax) |
| 4 | 54 | | { |
| 4 | 55 | | thirdMax = num; |
| 4 | 56 | | } |
| 17 | 57 | | } |
| | 58 | |
|
| 6 | 59 | | return thirdMax ?? firstMax.GetValueOrDefault(); |
| 8 | 60 | | } |
| | 61 | | } |