To prove safety offer 62. Child's Play

  1. Title: Children's Day each year, cow-off will prepare some small gifts to visit the orphanage children, this year is also true. As an experienced veteran off HF cattle, naturally we prepared some games. Among them, there is a game like this: First, let the children surrounded by a large circle. He then randomly assigned a number m, so that number of children 0 gettin number. Cried every time m-1 the children sing a song to be out of the line, then any of the gift box in choosing a gift, and not return to the circle, starting with his next child, continue 0 ... m -1 number of packets .... go on .... until the last remaining child, you can not perform, and get the cattle off the rare "Detective Conan" Collector's Edition (limited places oh !! ^ _ ^). You want to try next, which the children will get the gifts it? (NOTE: The number of children is from 0 to n-1)

     

    If there are no children, please return -1

  2. Thinking
    1. Maintenance circle the size of a vector, each circle is calculated from the index out
  3. Code
    class Solution {
    public:
        int LastRemaining_Solution(int n, int m)
        {
            if (n == 0)
                return -1;
            vector<int> numbers;
            for (int i = 0; i < n; i++)
                numbers.push_back(i);
            int k;
            int startIndex = 0;
            while (numbers.size() > 1) {
                k = (startIndex+m-1)%numbers.size();
                cout << "erase index number:" << k << endl;
                numbers.erase(numbers.begin()+k);
                startIndex = k;
            }
            return numbers[0];
        }
    };

     

Published 141 original articles · won praise 5 · Views 7474

Guess you like

Origin blog.csdn.net/Alexia23/article/details/104095184