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(设计的魅力)