# 62.圆圈中最后剩下的数字

### 一、 题目

0,1,···,n-1这n个数字排成一个圆圈，从数字0开始，每次从这个圆圈里删除第m个数字（删除后从下一个数字开始计数）。求出这个圆圈里剩下的最后一个数字。

例如，0、1、2、3、4这5个数字组成一个圆圈，从数字0开始每次删除第3个数字，则删除的前4个数字依次是2、0、4、1，因此最后剩下的数字是3。

示例 1：

输入: n = 5, m = 3

输出: 3

示例 2：

输入: n = 10, m = 17

输出: 2   限制：

1 <= n <= 10^5 1 <= m <= 10^6

来源：力扣（LeetCode）

链接：<https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof>

著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

### 二、 解法

#### 超时

```
func lastRemaining(_ n: Int, _ m: Int) -> Int {
    var right = m - 1
    var nums: [Int] = Array(0..<n)
    
    while nums.count > 1 {
        right = (right < nums.count) ? right : (right % nums.count)
        
        nums.remove(at: right)
        
        right += (m - 1)
    }
    
    return nums[0]
}
```

#### 数学解法

[能力有限。理解不能](https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/solution/javajie-jue-yue-se-fu-huan-wen-ti-gao-su-ni-wei-sh/)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/shu-ju-jie-gou-yu-suan-fa/jian-zhi-offerswift/62.-yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
