博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode -- Increasing Triplet Subsequence
阅读量:4624 次
发布时间:2019-06-09

本文共 1503 字,大约阅读时间需要 5 分钟。

Question:

Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.

Formally the function should:

Return true if there exists 
i, j, k 
such that 
arr[i] < 
arr[j] < 
arr[k] given 0 ≤ 
i < 
j < 
k ≤ 
n-1 else return false.

 

Your algorithm should run in O(n) time complexity and O(1) space complexity.

Examples:

Given [1, 2, 3, 4, 5],
return true.

Given [5, 4, 3, 2, 1],

return false.

 

Analysis:

 给出一个未排序的数组,判断该数组中是否存在一个长度为3的递增数组。

要求算法时间复杂度为O(n),空间复杂度为O(1).

 

 思路:

1. 最容易想到的思路就是3层for循环,先找出两个递增的序列,然后第三个数字比第二个数字的序号大,因此三层for循环可以很容易的解决,但是由于题目要求时间复杂度为O(n)。而这个思路的复杂度最好为O(1)前三个就符合条件,这样就返回true了,最差为O(n3)所有的都不符合条件,知道最后才会返回false。空间复杂度为0.不符合要求,但还是写上试了一下,没想到真的没有TLE!

Answer:

public class Solution {    public boolean increasingTriplet(int[] nums) {        if(nums == null || nums.length < 3)            return false;        for(int i=0; i
nums[i]) { for(int k=j+1; k
nums[j]) return true; } } } } return false; }}

 

2. 题目中要求时间复杂度为O(n),因此只能遍历数组一遍而不能有嵌套for循环。同时空间复杂度为O(1),所以我们使用两个变量,第一个变量保存最小的值,第二个变量保存次小的值,当下面的数组元素有一个比当前两个变量值都大的话,就会返回true。

Answer:

public class Solution {    public boolean increasingTriplet(int[] nums) {       if(nums == null || nums.length < 3)            return false;        int min = Integer.MAX_VALUE;        int nextMin = Integer.MAX_VALUE;        for(int i=0; i

 

转载于:https://www.cnblogs.com/little-YTMM/p/5212667.html

你可能感兴趣的文章
大端小端
查看>>
IntelliJ IDEA 把java项目导出成可执行的jar
查看>>
DynamicReports
查看>>
[Openstack] Expecting an auth URL via either --os-auth-url or env[OS_AUTH_URL]
查看>>
How to Create Modifiers Using the API QP_MODIFIERS_PUB.PROCESS_MODIFIERS
查看>>
待飞笔记(第一天 )
查看>>
解惑好文:移动端H5页面高清多屏适配方案
查看>>
traefik添加多证书
查看>>
PhantomJs 笔记
查看>>
js设计模式--语言类型
查看>>
C#多线程之二:ManualResetEvent和AutoResetEvent
查看>>
忽略UserInterfaceState.xcuserstate
查看>>
ReactNative--Flexbox布局
查看>>
java实现读取文件大全
查看>>
[Cordova] 无法显示Alert视窗
查看>>
借助过度区选择阈值
查看>>
评论列表显示及排序,个人中心显示
查看>>
JavaWeb学习笔记总结 目录篇
查看>>
C#根据html生成PDF
查看>>
Neutron SDN 手动实现手册
查看>>