334. Increasing Triplet Subsequence

LeetCode medium original: C# #array #backtracking #csharp #leetcode #medium
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.

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

Exemple:

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# solution

correspondant/original
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++ solution

brouillon automatique, à relire avant soumission
#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 solution

correspondant/original
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 solution

correspondant/original
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 solution

correspondant/original
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 solution

correspondant/original
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 или аналогичный максимум для выбранного языка программирования). Эти переменные будут хранить минимальные значения, необходимые для проверки существования возрастающей тройки.

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

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

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

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

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

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

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

😎

Vacancies for this task

offres actives with overlapping task tags are affichés.

Toutes les offres
Il n'y a pas encore d'offres actives.