leecode 解题总结:334. Increasing Triplet Subsequence

来源:互联网 发布:c 代理商系统源码 编辑:程序博客网 时间:2024/06/10 17:57
#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*问题: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.分析:题目是让你判断未排序的数组中是否存在着长度至少为3的递增子序列。算法运行时间为O(n),只允许使用常量空间。最简单的方法:排序,然后寻找是否存在长度为3的递增子序列,时间复杂度为O(NlogN)这里不允许使用排序,难道是位图,统计排序。直接设定一个计数器,如果当前元素大于前面的元素,计数器累加;如果累加到3,说明存在;如果当前元素<=前面的元素,则计数器变成1,重新统计注意:题目中没有要求这三个元素的下标间隔1所以问题变成了求递增子序列的长度,如果递增自学的最大长度 > =3 ,则符合条件。但是之前用动态规划,需要设置一个dp数组来做。输入:5(元素个数)1 2 3 4 555 4 3 2 1输出:truefalse关键:参考解法:http://www.cnblogs.com/zhoudayang/p/5246148.html1 维护min1,min2两个最小数,其中min1 < min2,如果当前数< min1,更新min1;如果 min1 <= 当前数 <= min2,更新min2为当前数否则,说明当前数大于这两个数本质上需要维护两个较小的数*/class Solution {public:    bool increasingTriplet(vector<int>& nums) {        if(nums.empty()){return false;}int size = nums.size();int min1 = INT_MAX;int min2 = INT_MAX;for(int i = 0 ; i < size ; i++){if(nums.at(i) <= min1){min1 = nums.at(i);}else if(nums.at(i) <= min2){min2 = nums.at(i);}else{return true;}}return false;    }};void process(){ vector<int> nums; int value; int num; Solution solution; bool result; while(cin >> num ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } result = solution.increasingTriplet(nums); if(result) { cout << "true" << endl; } else { cout << "false" << endl; } }}int main(int argc , char* argv[]){process();getchar();return 0;}

0 0