Leetcode Self Crossing
来源:互联网 发布:linux tomcat常用命令 编辑:程序博客网 时间:2024/04/29 01:45
Leetcode Self Crossing,本题的关键是找出区域的几种状态,以及一些边界情况。
区域的状态有
- 区域越来越大,在状态下我们只有保证有x[index] > x[index - 2]即可。
- 区域越来越小,在此状态下,需要维护一个最大值与最小值,在一般情况大有x[index] < x[index - 2]即可,但是存在一些边界情况需要了解。
边界状态有
- 在index == 3时,进入越来越小的状态时,如: 2, 2, 3, 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 1result: 0
0 0
- [leetcode]335. Self Crossing
- [LeetCode]Self Crossing
- leetcode 335. Self Crossing
- [LeetCode] 335. Self Crossing
- leetcode - Self Crossing
- [leetcode] 335. Self Crossing
- [leetcode] Self Crossing
- [LeetCode 335] Self Crossing
- LeetCode Self Crossing
- [leetcode-335]Self Crossing
- Leetcode Self Crossing
- [LeetCode] Self Crossing
- leetcode.335. Self Crossing
- Leetcode:335. Self Crossing
- LeetCode-335.Self Crossing
- LeetCode Self Crossing
- LeetCode 335. Self Crossing
- [LeetCode]335. Self Crossing
- POJ 3373 Changing Digits
- RStudio快捷键
- 使用Nexus创建Maven私有仓库
- centos6环境创建局域网http方式的yum源
- setResult与setResultData混淆
- Leetcode Self Crossing
- 初学android开发--day07
- char[],char *,string之间转换
- 62. Unique Paths
- c/c++基础知识点
- PHPStorm获取免费社区激活
- k-means确定初始中心值的方法
- 观察者模式
- Android开发 MeasureSpec介绍