LeetCode -- Increasing Triplet Subsequence
2016-02-24 13:44
686 查看
Question:
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Your algorithm should run in O(n) time complexity and O(1) space complexity.
Examples:
Given
return
Given
return
Analysis:
给出一个未排序的数组,判断该数组中是否存在一个长度为3的递增数组。
要求算法时间复杂度为O(n),空间复杂度为O(1).
思路:
1. 最容易想到的思路就是3层for循环,先找出两个递增的序列,然后第三个数字比第二个数字的序号大,因此三层for循环可以很容易的解决,但是由于题目要求时间复杂度为O(n)。而这个思路的复杂度最好为O(1)前三个就符合条件,这样就返回true了,最差为O(n3)所有的都不符合条件,知道最后才会返回false。空间复杂度为0.不符合要求,但还是写上试了一下,没想到真的没有TLE!
Answer:
2. 题目中要求时间复杂度为O(n),因此只能遍历数组一遍而不能有嵌套for循环。同时空间复杂度为O(1),所以我们使用两个变量,第一个变量保存最小的值,第二个变量保存次小的值,当下面的数组元素有一个比当前两个变量值都大的话,就会返回true。
Answer:
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.
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.length; i++) { for(int j=i+1; j<nums.length; j++) { if(nums[j] > nums[i]) { for(int k=j+1; k<nums.length; k++) { if(nums[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<nums.length; i++) { if(nums[i] <= min) min = nums[i]; else if(nums[i] <= nextMin) nextMin = nums[i]; else return true; } return false; } }
相关文章推荐
- iPhone6中获取到的UITableViewCell的size.width为啥还是320?
- UEditor配置-上传图片或文件时提示后端配置未正常加载
- 带按钮监听机制的简单java GUI
- 关于enumeration value 'xxxxx' not handled in switch的警告
- 范围最小值查询 RMQ (Range Minimum Query)
- SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"
- 使用require.js
- uvaoj-1594:ducci sequence
- perl HTML::TreeBuilder::XPath
- poj 1679 The Unique MST(次小生成树)
- 【CodeForces 622A】Infinite Sequence
- UICollectionView 布局
- Result Maps collection does not contain value for...
- [Locked] Count Univalue Subtrees
- UITableViewHeaderFooterView的使用+自己主动布局
- handler机制的原理
- 【bzoj1570】[JSOI2008]Blue Mary的旅行 最大流
- openquery教程
- hibernate使用sqlQuery查询mysql数据库时别名问题
- 蓝牙学习之①:调戏小米手环