Skip to content

Commit 2e2934d

Browse files
committed
Add solution 390
1 parent e3100de commit 2e2934d

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# [390. Elimination Game](https://leetcode.com/problems/elimination-game/)
2+
3+
4+
## 题目
5+
6+
You have a list `arr` of all integers in the range `[1, n]` sorted in a strictly increasing order. Apply the following algorithm on `arr`:
7+
8+
- Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
9+
- Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.
10+
- Keep repeating the steps again, alternating left to right and right to left, until a single number remains.
11+
12+
Given the integer `n`, return *the last number that remains in* `arr`.
13+
14+
**Example 1:**
15+
16+
```
17+
Input: n = 9
18+
Output: 6
19+
Explanation:
20+
arr = [1, 2,3, 4,5, 6,7, 8,9]
21+
arr = [2,4, 6,8]
22+
arr = [2, 6]
23+
arr = [6]
24+
25+
```
26+
27+
**Example 2:**
28+
29+
```
30+
Input: n = 1
31+
Output: 1
32+
33+
```
34+
35+
**Constraints:**
36+
37+
- `1 <= n <= 109`
38+
39+
## 题目大意
40+
41+
列表 arr 由在范围 [1, n] 中的所有整数组成,并按严格递增排序。请你对 arr 应用下述算法:
42+
43+
- 从左到右,删除第一个数字,然后每隔一个数字删除一个,直到到达列表末尾。
44+
- 重复上面的步骤,但这次是从右到左。也就是,删除最右侧的数字,然后剩下的数字每隔一个删除一个。
45+
- 不断重复这两步,从左到右和从右到左交替进行,直到只剩下一个数字。
46+
47+
给你整数 n ,返回 arr 最后剩下的数字。
48+
49+
## 解题思路
50+
51+
- 模拟题。按照题意,第一轮从左往右删除数字,第二轮从右往左删除数字。题目要求最后剩下的数字,模拟过程中不需要真的删除元素。只需要标记起始元素,该轮步长和方向即可。最后总元素只剩下一个即为所求。
52+
53+
## 代码
54+
55+
```go
56+
package leetcode
57+
58+
func lastRemaining(n int) int {
59+
start, dir, step := 1, true, 1
60+
for n > 1 {
61+
if dir { // 正向
62+
start += step
63+
} else { // 反向
64+
if n%2 == 1 {
65+
start += step
66+
}
67+
}
68+
dir = !dir
69+
n >>= 1
70+
step <<= 1
71+
}
72+
return start
73+
}
74+
```
75+
76+
77+
----------------------------------------------
78+
<div style="display: flex;justify-content: space-between;align-items: center;">
79+
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0389.Find-the-Difference/">⬅️上一页</a></p>
80+
<p><a href="https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0391.Perfect-Rectangle/">下一页➡️</a></p>
81+
</div>

0 commit comments

Comments
 (0)