334. Increasing Triplet Subsequence

LeetCode medium original: C# #array #backtracking #csharp #leetcode #medium
El texto de la tarea se traduce del ruso para el idioma seleccionado. El código no cambia.

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

Ejemplo:

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# solución

coincidente/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++ solución

borrador automático, revisar antes de enviar
#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 solución

coincidente/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 solución

coincidente/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 solución

coincidente/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 solución

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

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

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

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

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

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

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

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

😎

Vacantes para esta tarea

Se muestran vacantes activas con etiquetas coincidentes.

Todas las vacantes
Todavía no hay vacantes activas.