Sword refers to offer—62. Children's game (the last remaining number in the circle)—Analysis and code (Java)

@ toc

1. Title

Every June 1st Children's Day, Niuke will prepare some small gifts to visit the children in the orphanage, and this is also true this year. As a senior veteran of Niu Ke, HF naturally prepared some small games. Among them, there is a game like this: First, let the children form a big circle. Then, he randomly designated a number m, and let the child number 0 start reporting. Every time the child who shouts m-1 has to go out to sing a song, and then he can choose any gift in the gift box, and he does not return to the circle again. Starting from his next child, continue 0… m-1 Report the number... Keep going... until the last kid is left, you don't need to perform, and you can get the valuable "Detective Conan" Collector's Edition (the quota is limited!! _ ). Please try to think, which kid will get this gift? (Note: Children’s numbers are from 0 to n-1)

If there are no children, please return -1.

Two, analysis and code

1. Ring Linked List Simulation

(1) Thinking

The most straightforward method is to simulate the circle in a circular linked list. At this time, the time complexity is O(mn) and the space complexity is O(n).

(2) Code

public class Solution {
    
    
    public int LastRemaining_Solution(int n, int m) {
    
    
        if (n < 1)
            return -1;
        if (n == 1)
            return 0;
        
        ListNode head = new ListNode(0);
        ListNode pre = head;
        ListNode node = null;
        for (int i = 1; i < n; i++) {
    
    
            node = new ListNode(i);
            pre.next = node;
            pre = node;
        }
        node.next = head;
        
        while (node.next != node) {
    
    
            for (int i = 0; i < m - 1; i++)
                node = node.next;
            node.next = node.next.next;
        }
        
        return node.val;
    }
}

class ListNode {
    
    
    int val;
    ListNode next = null;

    ListNode(int val) {
    
    
        this.val = val;
    }
}

(3) Results

Running time: 28ms, occupied memory: 9420k.

2. Recurrence formula

First, mathematically induce the recurrence formula of the remaining numbers. For the specific process, please refer to the book "Sword Finger Offer". The formula obtained is:

f(n,m)=0, n=1  
f(n,m)=[f(n-1,m)+m]%n, n>1  

Combined with the recursive formula, the result can be quickly calculated through recursion or loop.

(2) Code

public class Solution {
    
    
    public int LastRemaining_Solution(int n, int m) {
    
    
        if (n < 1)
            return -1;
        int num = 0;
        for (int i = 2; i <= n; i++)
            num = (num + m) % i;
        return num;
    }
}

(3) Results

Running time: 18ms, occupied memory: 9204k.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/112155771