Leetcode Self Crossing

Leetcode Self Crossing,本题的关键是找出区域的几种状态,以及一些边界情况。

区域的状态有
  1. 区域越来越大,在状态下我们只有保证有x[index] > x[index - 2]即可。
  2. 区域越来越小,在此状态下,需要维护一个最大值与最小值,在一般情况大有x[index] < x[index - 2]即可,但是存在一些边界情况需要了解。
边界状态有
  1. 在index == 3时,进入越来越小的状态时,如: 2, 2, 3, 2,区域范围计算。
  2. 在index > 3时,进入越来越小的状态时,区域范围计算。

相关代码如下:

#include<iostream>
#include<vector>

using namespace std;
/**
 * The basic method of this problem is divide the state into two kind.
 * One is that the square is bigger and bigger.
 * One is that the square is smaller and smaller.
 *
 * In the first condition, we just make sure the x[index] > x[index - 2] can
 * fullfil this constraint.
 * In the second condition, we need keep the max size of the square, which need
 * to calculate the square size each step.
 */
class Solution {
public:
    bool isSelfCrossing(vector<int>& x) {
        if (x.size() <= 3) {
            return false;
        }
        int state = 0;
        int max1 = 0;
        int max2 = 0;
        if (x[2] <= x[0]) {
            state = 1;
            max1 = x[1];
            max2 = x[2];
        }
        for (int idx = 3; idx < x.size(); idx++) {
            // The first condition, the square bigger and bigger
            if (state == 0) {
                if (x[idx] <= x[idx - 2]) {
                    state = 1;
                    // state transform calculate the square size
                    if ((idx == 3 && x[idx] == x[idx - 2]) ||
                            (idx >= 4 && x[idx] >= x[idx - 2] - x[idx - 4])) {
                        max1 = x[idx - 1] - x[idx - 3];
                    } else {
                        max1 = x[idx - 1];
                    }
                    max2 = x[idx];
                }
            } else {
                // calculate the square size
                if (x[idx] < max1) {
                    int tmp = max2;
                    max2 = x[idx];
                    max1 = tmp;
                } else {
                    return true;
                }
            }
        }
        return false;
    }
};

int main(int argc, char* argv[]) {
    Solution so;
    vector<int> test;
    for (int i = 1; i < argc; i++) {
        test.push_back(atoi(argv[i]));
    }
    cout<<"result: "<<so.isSelfCrossing(test)<<endl;
    return 0;
}
测试:
./a.out 1 1 2 2 3 3 4 4 10 4 4 3 3 2 2 1 1
result: 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值