334. Increasing Triplet Subsequence

LeetCode medium original: C# #array #backtracking #csharp #leetcode #medium
Task text is translated from Russian for the selected interface language. Code is left unchanged.

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

Example:

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

matched/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

auto-draft, review before submit
#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

matched/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

matched/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

matched/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

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

Итерация по 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

Active vacancies with overlapping task tags are shown.

All vacancies
There are no active vacancies yet.