Processing math: 100%
1 Star 0 Fork 0

wxyfmq123456/leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
.github
.vscode
91
assets
backlog
collections
daily
problems
1.two-sum.en.md
1.two-sum.md
100.same-tree.md
1004.max-consecutive-ones-iii.md
101.symmetric-tree.md
1011.capacity-to-ship-packages-within-d-days-en.md
1011.capacity-to-ship-packages-within-d-days.md
1014.best-sightseeing-pair.md
1015.smallest-integer-divisible-by-k.md
1019.next-greater-node-in-linked-list.md
102.binary-tree-level-order-traversal.md
1020.number-of-enclaves.md
1023.camelcase-matching.md
103.binary-tree-zigzag-level-order-traversal.md
1031.maximum-sum-of-two-non-overlapping-subarrays.md
1032.stream-of-characters.md
104.maximum-depth-of-binary-tree.md
1043.partition-array-for-maximum-sum.md
108.convert-sorted-array-to-binary-search-tree.md
109.Convert-Sorted-List-to-Binary-Search-Tree.md
11.container-with-most-water.md
1104.path-in-zigzag-labelled-binary-tree.md
1128.number-of-equivalent-domino-pairs.md
1129.shortest-path-with-alternating-colors.md
113.path-sum-ii.md
1131.maximum-of-absolute-value-expression.md
1138.alphabet-board-path.md
1168.optimize-water-distribution-in-a-village-en.md
1168.optimize-water-distribution-in-a-village.md
1178.number-of-valid-words-for-each-puzzle.md
1186.maximum-subarray-sum-with-one-deletion.md
1203.sort-items-by-groups-respecting-dependencies.md
121.best-time-to-buy-and-sell-stock.md
1218.longest-arithmetic-subsequence-of-given-difference.md
122.best-time-to-buy-and-sell-stock-ii.md
1227.airplane-seat-assignment-probability.md
124.binary-tree-maximum-path-sum.md
125.valid-palindrome.md
1255.maximum-score-words-formed-by-letters.md
1260.shift-2d-grid.md
1261.find-elements-in-a-contaminated-binary-tree.md
1262.greatest-sum-divisible-by-three.md
128.longest-consecutive-sequence.md
129.sum-root-to-leaf-numbers.md
1297.maximum-number-of-occurrences-of-a-substring.md
130.surrounded-regions.md
131.palindrome-partitioning.md
1310.xor-queries-of-a-subarray.md
132.palindrome-partitioning-ii.md
1332.remove-palindromic-subsequences.md
1334.find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.md
136.single-number.md
1371.find-the-longest-substring-containing-vowels-in-even-counts.en.md
1371.find-the-longest-substring-containing-vowels-in-even-counts.md
1381.design-a-stack-with-increment-operation.md
139.word-break.md
140.word-break-ii.md
142.Linked-List-Cycle-II.md
1423.maximum-points-you-can-obtain-from-cards.md
1435.jump-game-iv.md
1438.longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.md
144.binary-tree-preorder-traversal.md
1449.form-largest-integer-with-digits-that-add-up-to-target.md
145.binary-tree-postorder-traversal.md
146.lru-cache.md
147.insertion-sort-list.md
1494.parallel-courses-ii.md
15.3sum.md
150.evaluate-reverse-polish-notation.md
152.maximum-product-subarray.md
1521.find-a-value-of-a-mysterious-function-closest-to-target.md
1526.minimum-number-of-increments-on-subarrays-to-form-a-target-array.md
153.find-minimum-in-rotated-sorted-array.md
154.find-minimum-in-rotated-sorted-array-ii.md
155.min-stack.md
1558.minimum-numbers-of-function-calls-to-make-target-array.md
1574.shortest-subarray-to-be-removed-to-make-array-sorted.md
1589.maximum-sum-obtained-of-any-permutation.md
160.Intersection-of-Two-Linked-Lists.md
1631.path-with-minimum-effort.md
1649.create-sorted-array-through-instructions.md
1658.minimum-operations-to-reduce-x-to-zero.md
167.two-sum-ii-input-array-is-sorted.md
1671.minimum-number-of-removals-to-make-mountain-array.md
169.majority-element.md
1697.checking-existence-of-edge-length-limited-paths.md
17.Letter-Combinations-of-a-Phone-Number.md
1713.minimum-operations-to-make-a-subsequence.md
172.factorial-trailing-zeroes.md
1723.find-minimum-time-to-finish-all-jobs.md
1737.change-minimum-characters-to-satisfy-one-of-three-conditions.md
1787.make-the-xor-of-all-segments-equal-to-zero.md
1834.single-threaded-cpu.md
1835.find-xor-sum-of-all-pairs-bitwise-and.md
1871.jump-game-vii.md
1872.stone-game-viii.md
1899.merge-triplets-to-form-target-triplet.md
19.removeNthNodeFromEndofList.md
190.reverse-bits.md
1904.the-number-of-full-rounds-you-have-played.md
1906.minimum-absolute-difference-queries.md
191.number-of-1-bits.md
1970.last-day-where-you-can-still-cross.md
198.house-robber.en.md
198.house-robber.md
199.binary-tree-right-side-view.md
2.add-two-numbers.en.md
2.add-two-numbers.md
20.valid-parentheses.md
200.number-of-islands.md
2008.maximum-earnings-from-taxi.md
2009.minimum-number-of-operations-to-make-array-continuous.md
201.bitwise-and-of-numbers-range.md
2025.maximum-number-of-ways-to-partition-an-array.md
203.remove-linked-list-elements.md
2030.smallest-k-length-subsequence-with-occurrences-of-a-letter.md
206.reverse-linked-list.md
208.implement-trie-prefix-tree.md
209.minimum-size-subarray-sum.md
21.merge-two-sorted-lists.md
211.add-and-search-word-data-structure-design.md
212.word-search-ii.md
215.kth-largest-element-in-an-array.md
219.contains-duplicate-ii.md
22.generate-parentheses.md
220.contains-duplicate-iii.md
221.maximal-square.md
226.invert-binary-tree.md
227.basic-calculator-ii.md
229.majority-element-ii.md
23.merge-k-sorted-lists.md
230.kth-smallest-element-in-a-bst.md
232.implement-queue-using-stacks.md
236.lowest-common-ancestor-of-a-binary-tree.md
238.product-of-array-except-self.md
239.sliding-window-maximum.md
24.swapNodesInPairs.md
240.search-a-2-d-matrix-ii.md
25.reverse-nodes-in-k-groups-en.md
25.reverse-nodes-in-k-groups.md
26.remove-duplicates-from-sorted-array.md
263.ugly-number.md
279.perfect-squares.md
283.move-zeroes.md
29.divide-two-integers.md
295.find-median-from-data-stream.md
297.serialize-and-deserialize-binary-tree.md
3.longest-substring-without-repeating-characters.md
30.substring-with-concatenation-of-all-words.md
301.remove-invalid-parentheses.md
309.best-time-to-buy-and-sell-stock-with-cooldown.md
31.next-permutation.md
312.burst-balloons.md
32.longest-valid-parentheses.md
322.coin-change.md
328.odd-even-linked-list.md
33.search-in-rotated-sorted-array.md
330.patching-array.md
331.verify-preorder-serialization-of-a-binary-tree.md
334.increasing-triplet-subsequence.md
335.self-crossing.md
337.house-robber-iii.md
342.power-of-four.md
343.integer-break.md
349.intersection-of-two-arrays.md
365.water-and-jug-problem.md
371.sum-of-two-integers.md
378.kth-smallest-element-in-a-sorted-matrix.md
380.insert-delete-getrandom-o1.md
385.mini-parser.md
39.combination-sum.md
394.decode-string.md
4.median-of-two-sorted-arrays.md
40.combination-sum-ii.md
401.binary-watch.md
416.partition-equal-subset-sum.md
42.trapping-rain-water.en.md
42.trapping-rain-water.md
424.longest-repeating-character-replacement.md
437.path-sum-iii.md
438.find-all-anagrams-in-a-string.md
445.add-two-numbers-ii.md
454.4-Sum-ii.en.md
454.4-sum-ii.md
455.AssignCookies.md
456.132-pattern.md
457.circular-array-loop.md
46.permutations.md
460.lfu-cache.md
464.can-i-win.md
47.permutations-ii.md
470.implement-rand10-using-rand7.md
472.concatenated-words.md
473.matchsticks-to-square.md
474.ones-and-zeros-en.md
48.rotate-image.md
480.sliding-window-median.md
483.smallest-good-base.md
488.zuma-game.md
49.group-anagrams.md
493.reverse-pairs.md
494.target-sum.md
5.longest-palindromic-substring.md
50.pow-x-n.md
501.Find-Mode-in-Binary-Search-Tree-en.md
504.base-7.md
513.find-bottom-left-tree-value.md
516.longest-palindromic-subsequence.md
518.coin-change-2.md
52.N-Queens-II.md
525.contiguous-array.md
53.maximum-sum-subarray-cn.md
53.maximum-sum-subarray-en.md
547.friend-circles-en.md
547.friend-circles.md
55.jump-game.md
56.merge-intervals.md
560.subarray-sum-equals-k.en.md
560.subarray-sum-equals-k.md
5640.maximum-xor-with-an-element-from-array.md
57.insert-interval.md
575.distribute-candies.md
5775.minimum-skips-to-arrive-at-meeting-on-time.md
60.permutation-sequence.md
609.find-duplicate-file-in-system.md
61.Rotate-List.md
611.valid-triangle-number.md
62.unique-paths.md
63.unique-paths-ii.md
65.valid-number.md
66.plus-one.md
664.strange-printer.md
665.non-decreasing-array.md
673.number-of-longest-increasing-subsequence.md
679.24-game.md
686.repeated-string-match.md
714.best-time-to-buy-and-sell-stock-with-transaction-fee.md
715.range-module.md
718.maximum-length-of-repeated-subarray.md
721.accounts-merge.md
726.number-of-atoms.md
73.set-matrix-zeroes.md
735.asteroid-collision.md
75.sort-colors.md
754.reach-a-number.md
768.max-chunks-to-make-sorted-ii.md
78.subsets-en.md
78.subsets.md
785.is-graph-bipartite.md
79.word-search-en.md
79.word-search.md
790.domino-and-tromino-tiling.md
799.champagne-tower.md
80.remove-duplicates-from-sorted-array-ii.md
801.minimum-swaps-to-make-sequences-increasing.md
805.split-array-with-same-average.md
816.ambiguous-coordinates.md
820.short-encoding-of-words.md
821.shortest-distance-to-a-character.md
838.push-dominoes.md
839.similar-string-groups.md
84.largest-rectangle-in-histogram.md
85.maximal-rectangle.md
86.partition-list.md
87.scramble-string.md
873.length-of-longest-fibonacci-subsequence.md
874.walking-robot-simulation.md
875.koko-eating-bananas.md
877.stone-game.md
88.merge-sorted-array.md
886.possible-bipartition.md
887.super-egg-drop.md
895.maximum-frequency-stack.md
898.bitwise-ors-of-subarrays.md
90.subsets-ii-en.md
90.subsets-ii.md
900.rle-iterator.md
909.snakes-and-ladders.md
91.decode-ways.md
911.online-election.md
912.sort-an-array.md
92.reverse-linked-list-ii.md
932.beautiful-array.md
935.knight-dialer.md
94.binary-tree-inorder-traversal.md
947.most-stones-removed-with-same-row-or-column.md
95.unique-binary-search-trees-ii.md
959.regions-cut-by-slashes.md
96.unique-binary-search-trees.md
975.odd-even-jump.md
978.longest-turbulent-subarray.md
98.validate-binary-search-tree.md
987.vertical-order-traversal-of-a-binary-tree.md
995.minimum-number-of-k-consecutive-bit-flips.md
997.find-the-town-judge.md
Bus-Fare.md
Connected-Road-to-Destination.md
Increasing-Digits.md
Kth-Pair-Distance.md
Largest-Equivalent-Set-of-Pairs.md
Longest-Contiguously-Strictly-Increasing-Sublist-After-Deletion.md
Longest-Matrix-Path-Length.md
Minimum-Dropping-Path-Sum.md
Minimum-Light-Radius.md
Number-Stream-to-Intervals.md
Number-of-Substrings-with-Single-Character-Difference.md
Sort-String-by-Flipping.md
Ticket-Order.md
Triple-Inversion.md
binode-lcci.md
consecutive-wins.md
get-kth-magic-number-lcci.md
lcp20.meChtZ.md
lcp21.Za25hA.md
max-black-square-lcci.md
sub-sort-lcci.md
selected
templates
thinkings
.gitignore
CONTRIBUTING.en.md
CONTRIBUTING.md
Kapture 2020-08-19 at 11.37.36.gif
LICENSE.txt
README.en.md
README.md
SUMMARY.md
book.json
cover.jpg
donation.md
epilogue.md
introduction.md
package.json
thanksGiving.md
thanksGiving2.md
thanksGiving3.md
克隆/下载
838.push-dominoes.md 4.60 KB
一键复制 编辑 原始数据 按行查看 历史
robot 提交于 4年前 . feat: $838

题目地址(838. 推多米诺)

https://leetcode-cn.com/problems/push-dominoes/

题目描述

一行中有 N 张多米诺骨牌,我们将每张多米诺骨牌垂直竖立。

在开始时,我们同时把一些多米诺骨牌向左或向右推。

每过一秒,倒向左边的多米诺骨牌会推动其左侧相邻的多米诺骨牌。

同样地,倒向右边的多米诺骨牌也会推动竖立在其右侧的相邻多米诺骨牌。

如果同时有多米诺骨牌落在一张垂直竖立的多米诺骨牌的两边,由于受力平衡, 该骨牌仍然保持不变。

就这个问题而言,我们会认为正在下降的多米诺骨牌不会对其它正在下降或已经下降的多米诺骨牌施加额外的力。

给定表示初始状态的字符串 "S" 。如果第 i 张多米诺骨牌被推向左边,则 S[i] = 'L';如果第 i 张多米诺骨牌被推向右边,则 S[i] = 'R';如果第 i 张多米诺骨牌没有被推动,则 S[i] = '.'。

返回表示最终状态的字符串。

示例 1:

输入:".L.R...LR..L.."
输出:"LL.RR.LLRRLL.."

示例 2:

输入:"RR.L"
输出:"RR.L"
说明:第一张多米诺骨牌没有给第二张施加额外的力。

提示:

0 <= N <= 10^5
表示多米诺骨牌状态的字符串只含有 'L','R'; 以及 '.';

前置知识

  • 双指针
  • 哨兵

公司

  • 暂无

思路

首先最终的 dominoes 状态一定满足:

  • 如果该 domino 受力了(L 或者 R),那么最终状态一定是受力的状态。比如 domino 受力为 L,那么最终状态一定也是 L,R 也是同理。
  • 如果一个 domino 没有受力,那么其可能保持原样,也可能由于其他 domino 而导致其变为 L 或者 R

因此我们只需要探究字符串 dominoes 中的 "." 在最终是 L 还是 R 即可。这里有一个关键点:只有相邻的受力 dominoes 才会相互影响。比如 .L...R..L 那么:

  • 只有第一个 L 和 R 有可能有影响
  • R 和第二个 L 有影响
  • 第一个 L 和 第二个 L 没有影响,因为二者并不相邻

想清楚这些,我们的算法就比较简单了。

我们可以使用双指针。其中:

  • 左指针指向第一个受力 domino
  • 右指针指向下一个受力 domino

左指针和右指针之前的 domino(一定是 .),最终的状态由左右指针指向而定。

具体地:

  • 如果左指针是 L,右指针是 R,那么中间保持 . 不变
  • 如果左指针是 L,右指针是 L,那么中间都是 L
  • 如果左指针是 R,右指针是 R,那么中间都是 R
  • 如果左指针是 R,右指针是 L,那么中间左半部分是 R 有右部分是 L,最中间(如果中间的 domino 个数是奇数的话)是 .

为了简化判断,可以在 domino 前放一个 L,后放一个 R。

关键点

  • 只有相邻的受力 dominoes 才会相互影响
  • 使用哨兵简化操作

代码

  • 语言支持:Python3

Python3 Code:


class Solution:
    def pushDominoes(self, dominoes: str) -> str:
        dominoes = 'L' + dominoes + 'R'
        i = 0
        j = i + 1
        ans = ''
        while j < len(dominoes):
            if dominoes[j] == '.':
                j += 1
                continue
            count = (j - i - 1)
            if i != 0 :ans += dominoes[i]
            if dominoes[i] == 'L' and dominoes[j] == 'R':
                ans += '.' * count
            elif dominoes[i] == 'L' and dominoes[j] == 'L':
                ans += 'L' * count
            elif dominoes[i] == 'R' and dominoes[j] == 'R':
                ans += 'R' * count
            elif dominoes[i] == 'R' and dominoes[j] == 'L':
                ans += 'R' * (count//2) + '.'*(count%2) + 'L' * (count//2)
            i = j
            j += 1
        return ans



复杂度分析

令 n 为数组长度。

  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

此题解由 力扣刷题插件 自动生成。

力扣的小伙伴可以关注我,这样就会第一时间收到我的动态啦~

以上就是本文的全部内容了。大家对此有何看法,欢迎给我留言,我有时间都会一一查看回答。更多算法套路可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 40K star 啦。大家也可以关注我的公众号《力扣加加》带你啃下算法这块硬骨头。

关注公众号力扣加加,努力用清晰直白的语言还原解题思路,并且有大量图解,手把手教你识别套路,高效刷题。

Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wxyfmq123456/leetcode.git
git@gitee.com:wxyfmq123456/leetcode.git
wxyfmq123456
leetcode
leetcode
master

搜索帮助