334. Increasing Triplet Subsequence

LeetCode medium original: C# #array #backtracking #csharp #leetcode #medium
Il testo del problema è tradotto dal russo per la lingua selezionata. Il codice resta invariato.

Дан array целых чисел nums. return true, если существуют такие три индекса (i, j, k), что i < j < k и nums[i] < nums[j] < nums[k]. Если таких индексов не существует, return false.

Esempio:

Input: nums = [2,1,5,0,4,6]

Output: true

Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.

C# soluzione

abbinato/originale
public class Solution {
    public bool IncreasingTriplet(int[] nums) {
        int firstNum = int.MaxValue;
        int secondNum = int.MaxValue;
        
        foreach (int n in nums) {
            if (n <= firstNum) {
                firstNum = n;
            } else if (n <= secondNum) {
                secondNum = n;
            } else {
                return true;
            }
        }
        return false;
    }
}

C++ soluzione

bozza automatica, rivedere prima dell'invio
#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 bool IncreasingTriplet(vector<int>& nums) {
        int firstNum = int.MaxValue;
        int secondNum = int.MaxValue;
        
        foreach (int n in nums) {
            if (n <= firstNum) {
                firstNum = n;
            } else if (n <= secondNum) {
                secondNum = n;
            } else {
                return true;
            }
        }
        return false;
    }
}

Java soluzione

abbinato/originale
class Solution {
    public boolean increasingTriplet(int[] nums) {
        int first_num = Integer.MAX_VALUE;
        int second_num = Integer.MAX_VALUE;
        for (int n: nums) {
            if (n <= first_num) {
                first_num = n;
            } else if (n <= second_num) {
                second_num = n;
            } else {
                return true;
            }
        }
        return false;
    }
}

JavaScript soluzione

abbinato/originale
var increasingTriplet = function(nums) {
    let firstNum = Infinity;
    let secondNum = Infinity;
    
    for (let n of nums) {
        if (n <= firstNum) {
            firstNum = n;
        } else if (n <= secondNum) {
            secondNum = n;
        } else {
            return true;
        }
    }
    return false;
};

Python soluzione

abbinato/originale
class Solution:
    def increasingTriplet(self, nums: List[int]) -> bool:
        first_num = float('inf')
        second_num = float('inf')
        
        for n in nums:
            if n <= first_num:
                first_num = n
            elif n <= second_num:
                second_num = n
            else:
                return True
        return False

Go soluzione

abbinato/originale
func increasingTriplet(nums []int) bool {
    firstNum := int(^uint(0) >> 1)  // Maximum integer
    secondNum := int(^uint(0) >> 1) // Maximum integer
    
    for _, n := range nums {
        if n <= firstNum {
            firstNum = n
        } else if n <= secondNum {
            secondNum = n
        } else {
            return true
        }
    }
    return false
}

Algorithm

Инициализация переменных:

Создайте две переменные first_num и second_num и установите их значение на максимальное целое значение (Integer.MAX_VALUE или аналогичный максимум для выбранного языка программирования). Эти переменные будут хранить минимальные значения, необходимые для проверки существования возрастающей тройки.

Итерация по arrayу:

Пройдите по каждому elementу arrayа nums. Для каждого elementа выполните следующие проверки:

- если текущий element меньше или равен first_num, обновите first_num текущим elementом.

- иначе, если текущий element меньше или равен second_num, обновите second_num текущим elementом.

- иначе, если текущий element больше second_num, это означает, что найдена возрастающая тройка, поэтому return true.

Возврат результата:

Если после завершения итерации по arrayу не была найдена возрастающая тройка, return false.

😎

Vacancies for this task

offerte attive with overlapping task tags are mostrati.

Tutte le offerte
Non ci sono ancora offerte attive.