Open songyy5517 opened 6 months ago
Approach: Greedy Algorithm, always keep the first two smallest numbers
first
and second
to store the first and the second number in the array, and second
is behind first
, and second > first
;
first = num[0]; second = Integer.MAX_VALUE;
cur_num > second
, and second
must be behind first
, showing that there is a triplet [first, second, cur_num]
, and then return true
;
(2)If cur_num < first
, update the variable first = cur_num
;
(3)If cur_num > first (cur_num <= second)
, update the variable second = cur_num
, because the triplets in [first, second', num]
must be in [first, second, num]
, if second' < second
.false
.Complexity Analysis
class Solution {
public boolean increasingTriplet(int[] nums) {
// 思路:贪心算法。遍历数组的同时,保存当前递增最小的两个数。
// 1. 异常处理
if (nums == null || nums.length == 0)
return false;
// 2. 定义变量
// first: 递增序列的第一个数
// second: 递增序列的第二个数,若存在于数组中,则之前一定有元素小于second。
int first = nums[0], second = Integer.MAX_VALUE;
// 3. 遍历数组
for (int i = 0; i < nums.length; i++){
// 当前数字大于second时,存在三元子序列
if (nums[i] > second)
return true;
// 当前元素小于等于second,且小于等于first,则更新first,此时second还是没变
else if (nums[i] <= first)
first = nums[i];
// 当前元素大于first,小于等于second,更新second
else
second = nums[i];
}
return false;
}
}
2024/5/9
Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.
Example 1:
Example 2:
Example 3:
Intuition This problem is to determine whether a triplet exists. One idea is based on Greedy Algorithm. Specifially, we loop through the whole array while keeping the first two smallest numbers
[first, second]
in the array. During the travarsing process, we updatefirst
andsecond
constantly, if there exists an element greater thansecond
, there exists a triplet.