资讯专栏INFORMATION COLUMN

6leetcode機器移動

glumes / 2611人阅读

1 題目

There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot"s movement is the same for each move

## 2. 示例
Input: "UD"
Output: true 
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true
Input: "LL"
Output: false
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
2. 解答
var judgeCircle = function(moves) {
    let x = 0, y = 0;
    for (let move of moves) {
        switch(move) {
            case "U": y++ ;break;
            case "D": y-- ;break;
            case "L": x-- ;break;
            case "R": x++ ;break;
        }
    }
    return x === 0 && y === 0
};
Runtime: 68 ms, faster than 86.60% of JavaScript online submissions
for Robot Return to Origin. Memory Usage: 36.7 MB, less than 40.71% of
JavaScript online submissions for Robot Return to Origin.
3. 其他解法
const judgeCircle = (moves) => {
    return moves.split("")
        .reduce((p, m) => [p[0] + (m === "R") - (m === "L"), p[1] + (m === "U") - (m === "D")], [0, 0])
        .join("") === "00"
};

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/103156.html

相关文章

  • 80VPS:日本/香港CN2服務器600元/月,E5/16G/1TB/20M帶寬

    摘要:商家提供最多的還是和獨立服務器租用,之前部落主要分享他的主機,最近關注獨立服務器,比如中國香港,或者帶寬,可選防禦,現在系列香港或者日本服務器每月僅元起。本文於 2021-09-02 07:57 更新,部分內容具有時效性,如有失效,請留言 80VPS怎麼樣,80VPS好不好,80VPS是一家成立較早的綜合性網絡產品服務商,提供的產品包括域名註冊、虛擬主機、VPS、雲服務器和獨立服務器租...

    wuyangchun 评论0 收藏0
  • 修羅云:成立兩周年特惠,有深港IPCL、香港HKT、廣州、中山、徐州、杭州、佛山等,最低6折起

    摘要:修羅雲成立兩周年了風雨同舟,數次搬遷在此衷心感謝大家的陪伴官網優惠碼首月折,續費折廣州,中山,徐州,杭州,佛山獨立可用。修羅雲怎麼樣,修羅雲好不好,修羅雲是一家國內老牌商家,商家以銷售NAT機器起家,國內的中轉機相當不錯,給的帶寬都非常高,如果你是移動或是教育網到國外速度非常慢,可以使用他家的中轉機拉一下,直接起飛的感覺,商家目前推出兩周年活動,他家一般很少有活動,本次優惠為新購首月6折,續...

    Little_XM 评论0 收藏0
  • DMIT:國外高端VPS雲服務器特價優惠,美國/香港/日本可選,高端CN2 GIA優質線路大帶寬不限

    摘要:內存流量帶寬價格購買核不限月購買核不限月購買核不限月購買核不限月購買網絡測試查看含有美國洛杉磯標籤的文章美國洛杉磯查看含有洛杉磯標籤的文章洛杉磯高防日本東京查看含有香港標籤的文章香港 最近站長整理了一下DMIT商家的CN2 GIA特價優惠VPS雲服務器產品,主要是美國、香港、日本等地區的VPS雲服務器產品,線路方面依然非常優質,有需要國外優質線路VPS雲服務器的朋友可以關注一...

    qqlcbb 评论0 收藏0

发表评论

0条评论

glumes

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<