C + + Brush questions (3/100) Sudoku, stacks and queues

Source: Internet
Author: User

Basic operation of Stack

? s.size(): Returns the number of elements in the stack
? s.empty(): Determines whether the stack is empty, returns TRUE or False
? s.push(元素): Returns a mutable (modifiable) reference to the "element" at the top of the stack
? s.pop(): Delete top of stack element, type void, but does not return deleted element

? s.top(): Returns the top of the stack without deleting
? s1==s2: If established, indicates that each element in the S1 is equal to the corresponding element of S2 and returns TRUE or False

Topic 1: Implementing a queue with two stacks

https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&tPage=2&rp=2 &ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

Topic description Use two stacks to implement a queue, complete the queue push and pop operations. The elements in the queue are of type int. Ideas: Relatively simple, two stacks s1,s2 push when the S1 in the Push,pop, first S1 elements all push to S2, and then pop is the queue order. This problem can also be described as how to reverse the stack output
classsolution{ Public:    voidPushintnode)    {Stack1.push (node); }    intpop () { while(!Stack1.empty ())            {Stack2.push (Stack1.top ());        Stack1.pop (); }        intres =Stack2.top ();        Stack2.pop ();  while(!Stack2.empty ())            {Stack1.push (Stack2.top ());        Stack2.pop (); }        returnRes; }Private: Stack<int>Stack1; Stack<int>Stack2;};

Topic 2: Sliding window Maximum Value

https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788?tpId=13&tqId=11217&tPage=2&rp=2 &ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

The title describes the size of the given array and the sliding window, and finds the maximum value of the values in all the sliding windows. For example, if you enter the array {2,3,4,2,6,2,5,1} and the size of the sliding window 3, there are 6 sliding windows, their maximum value is {4,4,6,6,6,5}, and the sliding window for the array {2,3,4,2,6,2,5,1} has the following 6: {[ 2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[ 2,5,1]}. Idea: This question O (n*k) is very simple, but to O (n) There is a statement, O (n) method is two-way queue first look at my relatively frustrated version, with two queues:
classSolution { Public: Vector<int> Maxslidingwindow (vector<int>& Nums,intk) {Queue<int>Q; Deque<int>qmin; Vector<int>ans; if(nums.size () = =0|| k==0){            returnans; }         for(intI=0; i<k;i++){            if(Qmin.empty ()) {Qmin.push_back (nums[i]); }Else{                 while(!qmin.empty () &&qmin.back () <Nums[i]) qmin.pop_back ();            Qmin.push_back (Nums[i]);        } q.push (Nums[i]);        } ans.push_back (Qmin.front ());  for(intI=k;i<nums.size (); i++){            if(Qmin.front () = =Q.front ())            {Qmin.pop_front ();            } q.pop ();            Q.push (Nums[i]);  while(!qmin.empty () &&qmin.back () <Nums[i]) qmin.pop_back ();            Qmin.push_back (Nums[i]);        Ans.push_back (Qmin.front ()); }        returnans; }};

Then look at the online version of God: A double-ended queue, the code is also more concise than I ...

classSolution { Public: Vector<int> Maxinwindows (Constvector<int>& num, unsignedintsize) {deque<int>qmin; Vector<int>ans; intK =size; if(num.size () = =0|| size==0){            returnans; }         for(intI=0; I<num.size (); i++){        //whenever a new number comes in, if you find the subscript for the number of queue headers, which is the subscript for the leftmost number of the window, throw away            if(!qmin.empty () && qmin.front () = = i-k) Qmin.pop_front (); //throw away all the tail of the queue, which is smaller than the new number, and make sure the queue is descending             while(!qmin.empty () && num[qmin.back ()] <Num[i]) qmin.pop_back (); //Add new numberQmin.push_back (i); //the head of the queue is the first largest in the window            if((i +1) >= (int) k) Ans.push_back (Num[qmin.front ())); }        returnans; }};

Topic 3: Sudoku

Write a program that solves the Sudoku problem with filled spaces.

A Sudoku solution should follow the following rules:

    1. 1-9the number can appear only once per line.
    2. Numbers 1-9 can appear only once in each column.
    3. The numbers 1-9 3x3 can only appear once in each palace separated by a thick solid line.

The blank lattice is ‘.‘ represented by.

A Sudoku.

The answer is marked red.

Note:

    • The given Sudoku sequence contains only numbers 1-9 and characters ‘.‘ .
    • You can assume that a given Sudoku has only one solution.
    • The given Sudoku is always 9x9 the form.

Idea: Search for the title, in the position can fill a number, and then judge the legitimacy, if the legal from the state and then fill the next number.

Originally thought to use a A *, the results found that the direct search also did not time out, there is the original topic is void function, no return really uncomfortable, search if the recursive function does not return how do you know to find not ah.

Finally found that others forcibly changed the function of the example to bool type, and then can be over.

Finally review the single-digit int-"char is num+ ' 0 ', Char->int is str-' 0 '

classSolution { Public:    BOOLCheckisleagel (vector<vector<Char>>& Board,intXinty) {         for(intI=0;i<9; i++){            if(i!=x&&board[x][y]==Board[i][y]) {                return false ; }            if(i!=y&&board[x][y]==Board[x][i]) {                return false ; }        }         for(intI=3* (x/3);i<3* (x/3+1); i++){             for(intj=3* (y/3);j<3* (y/3+1); J + +){                if(x!=i&&y!=j&&board[x][y]==Board[i][j]) {                    return false ; }            }        }        return true ; }        BOOLSolvesudoku (vector<vector<Char>>&Board) {         for(intI=0;i<9; i++){             for(intj=0;j<9; j + +){                if(board[i][j]=='.'){                     for(intk=1; k<=9; k++) {Board[i][j]= k +'0' ; if(Checkisleagel (BOARD,I,J) &&Solvesudoku (board)) {                            return true ; } Board[i][j]='.' ; }                    return false ; }            }        }        return true ; }};

PS: Record two data structures of small top heap and large top heap (priority queue):
priority_queue<int, vector<int, less<int// Store small value, higher value, greater priority priority_queue<int, vector<int;, greater<int//  Store a large value, the lower the value, the higher the priority
  双向队列:
    1. Deq[]: Used to access a single element in a two-way queue.
    2. Deq.front (): Returns a reference to the first element.
    3. Deq.back (): Returns a reference to the last element.
    4. Deq.push_front (x): Inserts element x into the head of the bidirectional queue.
    5. Deq.pop_front (): POPs the first element of a bidirectional queue.
    6. Deq.push_back (x): Inserts element x into the tail of the bidirectional queue.
    7. Deq.pop_back (): pops up the last element of the bidirectional queue.
Some features of deque
    1. Support for random access, that is, support for [] and at (), but the performance of the vector is not good.
    2. Insert and delete operations can be done internally, but performance is less than list.
    3. Deque can quickly insert and delete elements at both ends, and vectors can only be performed at the end.
    4. The Deque element access and iterator operations are slightly slower because the internal structure of the deque is one more indirect process.
    5. The Deque iterator is a special smart pointer, not a generic pointer, and it needs to jump between different chunks.
    6. Deque can contain more elements, and its max_size may be larger because more than one piece of memory is used.
    7. Deque does not support control over the timing of capacity and memory allocation.
    8. Inserting and deleting elements in addition to the ends will cause any pointers, references, iterators that point to the deque element to fail. However, Deque's memory redistribution is superior to vector because its internal structure shows no need to copy all elements.
    9. Deque memory chunks are no longer being used, they are freed, and the deque memory size is reduced. However, it is not done and how to do this is defined by the actual operating version.
    10. Deque does not provide capacity operations: capacity () and reverse (), but vectors can.

C + + Brush questions (3/100) Sudoku, stacks and queues

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.