zoukankan      html  css  js  c++  java
  • [leetcode] 403. Frog Jump

    https://leetcode.com/contest/5/problems/frog-jump/

    这个题目,还是有套路的,之前做过一道题,好像是贪心性质,就是每次可以跳多远,最后问能不能跳到最右边,一会找一下这道题(找到了,就是这个55. Jump Game)。然后这道题,差不多是相同的意思,但是每次只能跳3个或者2个,跳了之后还要判断那个位置有没有石头,然后还要记录上一次跳的间隔,然后我就想到了要用map做一个位置到index的映射,主要用于o(1)的查找,可以用unordered_map来做,然后每个位置还要记录上一次跳的间隔,但是不用记住上一次的位置,考虑可以多次转移,然后每一个位置用set记录,上次的间隔。最后想一下,数据范围也就1000,应该很容易的就过了,就这样。

     1 class Solution {
     2 public:
     3      bool canCross(vector<int>& s) {
     4         int n = s.size();
     5         if(n == 1) return 1;
     6         if(s[0] + 1 != s[1]) return 0;
     7         vector<bool> res(n + 1, 0);
     8         res[1] = 1;
     9         set<int> se;
    10         set<int> a[n];
    11         map<int, int> m;
    12         for (int i = 0; i < n; i++) {se.insert(s[i]);
    13             m[s[i]] = i;
    14         }
    15         a[1].insert(1);
    16         for (int i = 1; i < n - 1; i++) {
    17             for (auto it = a[i].begin(); it != a[i].end(); it++) {
    18                 //cout << i << " " << *it << endl;
    19                 int cur = *it;
    20                 if(cur - 1 > 0) {
    21                     if(m.count(s[i] + cur - 1)) {
    22                         int t = m[s[i] + cur - 1];
    23                         a[t].insert(cur - 1);
    24                         res[t] = 1;
    25                     }
    26                 }
    27                 if(m.count(s[i] + cur)) {
    28                         int t = m[s[i] + cur];
    29                         a[t].insert(cur);
    30                         res[t] = 1;
    31                 }
    32                 if(m.count(s[i] + cur + 1)) {
    33                         int t = m[s[i] + cur + 1];
    34                         a[t].insert(cur + 1);
    35                         res[t] = 1;
    36                 }
    37 
    38             }
    39         }
    40         return res[n - 1];
    41     }
    42 };
  • 相关阅读:
    计算几何 val.3
    项目中常用的19条MySQL优化
    九年测试老鸟给测试新人的6条忠告
    敏捷软件测试常见的七个误区
    JEMTER简单的测试计划
    你真的会搭建测试环境吗?
    使用 Fiddler工具模拟post四种请求数据
    性能测试方案及性能测试流程
    Appium的环境搭建和配置
    Python :编写条件分支代码的技巧
  • 原文地址:https://www.cnblogs.com/y119777/p/5882697.html
Copyright © 2011-2022 走看看