414. Third Maximum Number

LeetCode easy оригинал: C# #array #csharp #easy #leetcode

Если задан целочисленный массив nums, верните третье максимальное число в этом массиве. Если третьего максимального числа не существует, верните максимальное число.

Пример:

Input: nums = [3,2,1]

Output: 1

C# решение

сопоставлено/оригинал
public class Solution {
    public int ThirdMax(int[] nums) {
        int? first = null;
        int? second = null;
        int? third = null;
        
        foreach (int num in nums) {
            if (num == first || num == second || num == third) {
                continue;
            }
            if (first == null || num > first) {
                third = second;
                second = first;
                first = num;
            } else if (second == null || num > second) {
                third = second;
                second = num;
            } else if (third == null || num > third) {
                third = num;
            }
        }
        
        return third ?? first.Value;
    }
}

C++ решение

auto-draft, проверить перед отправкой
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int ThirdMax(vector<int>& nums) {
        int? first = null;
        int? second = null;
        int? third = null;
        
        foreach (int num in nums) {
            if (num == first || num == second || num == third) {
                continue;
            }
            if (first == null || num > first) {
                third = second;
                second = first;
                first = num;
            } else if (second == null || num > second) {
                third = second;
                second = num;
            } else if (third == null || num > third) {
                third = num;
            }
        }
        
        return third ?? first.Value;
    }
}

Java решение

сопоставлено/оригинал
import java.util.HashSet;
import java.util.Set;

public class Solution {
    public int thirdMax(int[] nums) {
        Integer first = null;
        Integer second = null;
        Integer third = null;
        
        for (Integer num : nums) {
            if (num.equals(first) || num.equals(second) || num.equals(third)) {
                continue;
            }
            if (first == null || num > first) {
                third = second;
                second = first;
                first = num;
            } else if (second == null || num > second) {
                third = second;
                second = num;
            } else if (third == null || num > third) {
                third = num;
            }
        }
        
        return third != null ? third : first;
    }
}

JavaScript решение

сопоставлено/оригинал
function thirdMax(nums) {
    let first = null;
    let second = null;
    let third = null;
    
    for (const num of nums) {
        if (num === first || num === second || num === third) {
            continue;
        }
        if (first === null || num > first) {
            third = second;
            second = first;
            first = num;
        } else if (second === null || num > second) {
            third = second;
            second = num;
        } else if (third === null || num > third) {
            third = num;
        }
    }
    
    return third !== null ? third : first;
}

Python решение

сопоставлено/оригинал
def thirdMax(nums):
    first = second = third = None
    
    for num in nums:
        if num in (first, second, third):
            continue
        if first is None or num > first:
            third = second
            second = first
            first = num
        elif second is None or num > second:
            third = second
            second = num
        elif third is None or num > third:
            third = num
    
    return third if third is not None else first

Go решение

сопоставлено/оригинал
package main

import (
    "math"
)

func thirdMax(nums []int) int {
    first, second, third := math.MinInt64, math.MinInt64, math.MinInt64
    
    for _, num := range nums {
        if num == first || num == second || num == third {
            continue
        }
        if num > first {
            third = second
            second = first
            first = num
        } else if num > second {
            third = second
            second = num
        } else if num > third {
            third = num
        }
    }
    
    if third == math.MinInt64 {
        return first
    }
    return third
}

Algorithm

Инициализируйте три переменные для хранения первого, второго и третьего максимальных чисел, используя значения None или аналогичные значения.

Пройдитесь по массиву, обновляя переменные первого, второго и третьего максимальных чисел, избегая дубликатов.

Если третье максимальное число существует, верните его. В противном случае, верните первое максимальное число.

😎

Вакансии для этой задачи

Показаны активные вакансии с пересечением по тегам задачи.

Все вакансии
Активных вакансий пока нет.