设计的魅力6

2069. 模拟行走机器人 II
此题又是一道用全O(1)时间复杂度实现类中所有方法的题。坑也很多,包括但不限于,在step方法中就得把当前位置找出来,否则影响机器人当前朝向的判断。WA了几发,才发现一些细节上的错误。
Ruby解

class Robot

=begin
    :type width: Integer
    :type height: Integer
=end
    def initialize(width, height)
      @s = (width-1)*2+(height-1)*2
      @step = 0
      @width = width
      @height = height
      @p = [0,0]
      @cnt = 0
    end


=begin
    :type num: Integer
    :rtype: Void
=end
    def step(num)
      @step += num
      @cnt += 1
      t = @step % @s
      if t >= 1 && t <= @width - 1
        @p = [t,0]
      elsif t > @width - 1 && t <= @width - 1 + @height - 1
        @p = [@width - 1,t - @width + 1]
      elsif t > @width - 1 + @height - 1 && t <= 2*(@width - 1)+@height-1
        @p = [@width - 1 - (t - @width + 1 - @height + 1),@height-1]
      elsif t > 2*(@width - 1) + @height - 1
        @p = [0,@height - 1 - (t - 2*(@width - 1) - @height + 1)]
      else
        @p = [0,0]
      end
    end


=begin
    :rtype: Integer[]
=end
    def get_pos()
      @p
    end


=begin
    :rtype: String
=end
    def get_dir()
      if @p == [0,0] && @cnt == 0
        return "East"
      elsif @p == [0,0] && @cnt > 0
        return "South"
      elsif @p[0] > 0 && @p[1] == 0
        return "East"
      elsif @p[0] == @width - 1 && @p[1] > 0
        return "North"
      elsif @p[0] > 0 && @p[1] == @height - 1
        return "West"
      elsif @p[0] == 0 && @p[1] == @height - 1
        return "West"
      elsif @p[0] == 0 && @p[1] > 0
        return "South"
      end
    end


end

Leetcode 635 (设计的魅力5)
Leetcode 2590(设计的魅力4)
Leetcode 2166(设计的魅力3)
面试题03.03.堆盘子(设计的魅力2)
Leetcode 981 和 Leetcode 1797(设计的魅力)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Bookmarks 书签栏 入职 华为新员工小百科(刷新时间202003023) - 人才供应知多少 - 3MS知...
    Btrace阅读 5,296评论 0 0
  • 字符串 题目内容解法3 Longest Substring Without Repeating Characte...
    jluemmmm阅读 1,339评论 0 0
  • 序言: 为了免去以后自己寻找可能会比较麻烦,然后把所有的书写的简书分类分条目列出 Spring+SpringMVC...
    是小猪童鞋啦阅读 14,810评论 0 4
  • c++基础主要准备一下c++基于语法、数据结构(二叉树、链表)、面向对象、异步编程、网络编程,leetcode上找...
    自信侠阅读 3,226评论 0 1
  • Leetcode 题库链接[https://leetcode.com/problemset/all/]   断断续...
    xingzai阅读 3,342评论 0 0