Leetcode Interview Question 62. The last remaining number in the circle

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.

Input: n = 5, m = 3
Output: 3

Problem solving report

  • The number of n person is 0 , 1 , 2 , , n 1 0,1,2,\cdots,n-1 , delete the number as m 1 m-1 person, the next person deleted from k + 1 k+1 starts counting, the corresponding number sequence is m , m + 1 , , n 1 , 0 , , m 2 m,m+1,\cdots,n-1,0,\cdots,m-2
  • Remaining n 1 n-1 Make a mapping of the number of person, and map it into 0 , 1 , , n 2 0,1,\cdots,n-2 , then in the new sequence x x is the original sequence ( x + m ) % n (x+m) \% n
  • in other words, n 1 n-1 person last remaining number is x x , then corresponding n n The number of the last remaining person of people is ( x + m ) % n (x+m)\%n
  • make f ( n ) f(n) means n n number of the last person left, then f ( n ) = ( f ( n ) + m ) % n f(n)=(f(n)+m)\%n

Implementation code

  • Recursive
class Solution {
	public:
		int f(int n, int m) {
	        if (n == 1)
	            return 0;
	        int x = f(n - 1, m);
	        return (m + x) % n;
	    }
    	int lastRemaining(int n, int m) {
        	return f(n, m);
    	}
};
  • Iterate
class Solution {
public:
    int lastRemaining(int n, int m) {
        int ans=0;
        for(int i=2;i<=n;i++){
            ans=(ans+m)%i;
        }
        return ans;
    }
};
MD_
Published 139 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_27690765/article/details/105210599