LaiCode 376. Ascending Triple I

这篇博客介绍了如何利用双指针技术解决编程问题,具体是判断一个整数数组是否存在三个上升的索引i, j, k使得a[i] < a[j] < a[k]。通过设置small和medium两个变量,避免了三次循环,实现了O(n)的时间复杂度和O(1)的空间复杂度的解决方案。文章详细解释了三种情况,并给出了Java实现代码。
摘要由CSDN通过智能技术生成

LaiCode 376. Ascending Triple I

题目描述

Determine if the given integer array has three indices such that i < j < k and a[i] < a[j] < a[k].

Assumptions:

The given array is not null.
Examples:

{1, 5, 2, 4}, return true since i = 0, j = 2, k = 3

{4, 3, 2, 1}, return false

思路

参考了其他同学的解题思路, 解决此题不需要用3次for loop,设定两个变量small, medium,值均为Integer.MAX_VALUE,然后直接开始for (int num : array),分三种情况:

Case 1

num <= small, 则令small = num,即找到i。

Case 2

num > small && num <= medium,则令medium = num,即找到j。

Case 3

num > small && num > medium,则找到large/k,可以返回true。

Code

public class Solution {
  public boolean existIJK(int[] array) {
    if (array.length < 3){
      return false;
    }
    int s = Integer.MAX_VALUE;
    int m = Integer.MAX_VALUE;
    for (int num : array){
      if (num <= s){
        s = num;
      }
      if (num > s && num <= m){
        m = num;
      }
      if (num > s && num > m){
        return true;
      }
    }
    return false;
  }
}

//TC:O(n)
//SC:O(1)

时间复杂度为O(n),空间复杂度为O(1)。

因为觉得思路很好,有必要记录,因此写下这篇文章。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值