【LintCode】Pattern(C语言实现)

题目描述


Given a sequence of n integers a1, a2, …, an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.

n will be less than 20,000.

测试数据


Given nums = [1, 2, 3, 4]
return False // There is no 132 pattern in the sequence.

Given nums = [3, 1, 4, 2]
return True // There is a 132 pattern in the sequence: [1, 4, 2].

解题思路


找满足A[i] < A[k]

C实现代码


#include 
#define true 1
#define false 0
#define VSIZE 100
#define SSIZE 100
#define INT_MIN -10000000
typedef unsigned char bool;

typedef struct
{
    int data[VSIZE];
    int length;
}vector;

typedef struct
{
    int data[SSIZE];
    int top;
}stack;


bool solve(vector v)
{
    int third = INT_MIN;
    stack second;
    int i;
    second.top = -1;
    for(i = v.length - 1; i >= 0; --i)
    {
        //当前的数比third小,也肯定比栈里的数小,条件满足
        if(v.data[i] < third)
            return true;
        else
        {
            while(second.top != -1)
            {
                //如果当前的数比栈顶的数大,可以用栈顶的数更新
                //third,从而得到一个更大的third,加快算法速度
                if(second.data[second.top] < v.data[i])
                {
                    if(third < second.data[second.top])
                        third = second.data[second.top];
                    --second.top;
                }
                else
                    break;
            }
            second.data[++second.top] = v.data[i];
        }
    }
    return false;
}

int main(int argc, char *argv[])
{
    vector v;
    int i;
    while(~scanf("%d", &v.length))
    {
        for(i = 0; i < v.length; i++)
            scanf("%d", &v.data[i]);
        if(solve(v))
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}

你可能感兴趣的:(面试题)