LeetCode334. Increasing Triplet Subsequence完美解答
2016-04-07 18:50
423 查看
/**
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.
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
if (nums.size() < 3) {
return false;
}
int count = 1;
int min = nums[0];
int min2 = INT_MAX;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] > min2) {
return true;
}
else if (nums[i] < min) {
min = nums[i];
}
else if (nums[i] < min2 && nums[i] > min) {
min2 = nums[i];
}
}
return false;
}
};
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.
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
if (nums.size() < 3) {
return false;
}
int count = 1;
int min = nums[0];
int min2 = INT_MAX;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] > min2) {
return true;
}
else if (nums[i] < min) {
min = nums[i];
}
else if (nums[i] < min2 && nums[i] > min) {
min2 = nums[i];
}
}
return false;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- ruby 数组使用教程
- Ruby中的数组和散列表的使用详解
- C#实现AddRange为数组添加多个元素的方法
- C#比较二个数组并找出相同或不同元素的方法
- C#动态调整数组大小的方法
- Lua中调用C++函数示例
- 详解Lua中的数组概念知识
- Lua教程(一):在C++中嵌入Lua脚本
- Perl中的列表和数组学习笔记
- Lua教程(二):C++和Lua相互传递数据示例
- 探索PowerShell (八) 数组、哈希表(附:复制粘贴技巧)
- C#中数组初始化与数组元素复制的方法
- C#交错数组用法实例
- Linux Shell 数组建立及使用技巧
- PowerShell数组的一些操作技巧
- C#通过yield实现数组全排列的方法