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

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

原题链接在这里:

题目:

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.

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

Example 1:

Input: [1,2,3,4,5]Output: true

Example 2:

Input: [5,4,3,2,1]Output: false

题解:

Could use dp to track up to index i, the length of longest subarray. 

For all j from 0 to i, if nums[j]<nums[i], then dp[i] = Math.max(dp[i], dp[j]+1). If dp[i] >= 3, then return true.

Time Complexity: O(n^2). n = nums.length.

Space: O(n).

AC Java: 

1 class Solution { 2     public boolean increasingTriplet(int[] nums) { 3         if(nums == null || nums.length < 3){ 4             return false; 5         } 6          7         int len = nums.length; 8         int [] dp = new int[len]; 9         for(int i = 0; i
2){15 return true;16 }17 }18 }19 }20 21 return false;22 }23 }

Could use first and second variables to maintain the first smallest and second smallest number.

For each number in nums array, if num <= first, update first. Else if num <= second, update second. Else, this means that there are 2 increasing numbers smaller than current number before. Thus return true.

Time Complexity: O(n).

Space: O(1).

AC Java:

1 class Solution { 2     public boolean increasingTriplet(int[] nums) { 3         int first = Integer.MAX_VALUE; 4         int second = Integer.MAX_VALUE; 5         for(int num : nums){ 6             if(num <= first){ 7                 first = num; 8             }else if(num <= second){ 9                 second = num;10             }else{11                 return true;12             }13         }14         15         return false;16     }17 }

类似.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11450797.html

你可能感兴趣的文章
opencms忘记Admin用户登录密码解决方案
查看>>
forms组件
查看>>
create-react-app 配置sass
查看>>
02_关系数据库
查看>>
在win7电脑中如何查看运行进程的PID标识符
查看>>
[Vue] vue-cli3.0安装
查看>>
C++学习之字符串
查看>>
图像化列表
查看>>
2014年10月9日——语言基础2
查看>>
mysql查
查看>>
[正则表达式]难点和误区
查看>>
217. Contains Duplicate
查看>>
hadoop遇到问题总结
查看>>
Windows下手动安装redis服务
查看>>
把 MongoDB 当成是纯内存数据库来使用(Redis 风格)
查看>>
PyTorch 1.0 中文官方教程:使用ONNX将模型从PyTorch传输到Caffe2和移动端
查看>>
LeetCode 4Sum
查看>>
BBC-The Race and a quiz
查看>>
大端小端
查看>>
IntelliJ IDEA 把java项目导出成可执行的jar
查看>>