2020-04-10 11:40:30
Problem Description:
The n numbers 0,1,, n-1 are arranged in a circle, starting with the number 0, and deleting the mth number from this circle each time. Find the last number left in this circle.
For example, the 5 digits 0, 1, 2, 3, and 4 form a circle, and the third digit is deleted every time from the digit 0, then the first 4 digits deleted are 2, 0, 4, 1, and so on. The remaining number is 3.
Example 1:
Input: n = 5, m = 3 Output: 3
Example 2:
Input: n = 10, m = 17 Output: 2
limit:
1 <= n <= 10^5
1 <= m <= 10^6
Problem solving:
Use recursive solution to solve in O (n) time complexity.
Time complexity: O (n)
public int lastRemaining(int n, int m) { if (n == 1) return 0; return (lastRemaining(n - 1, m) + m) % n; }