The sword is an offer (five, vi), the queue is implemented with two stacks, the smallest number of the rotated array

Source: Internet
Author: User

Title Description

Implement a queue with two stacks to complete the push and pop operations of the queue. The elements in the queue are of type int.

A stack is the reverse of the queue, then a stack push into the first stack is "positive" come over.
The first stack is the one that saves the reverse sequence.
Each push into a number, you must first determine whether the Stack2 "positive" sequence is empty, not empty to restore "anti-sequence", but also stack1 push into all the stack2.
Each pop a number, the stack1 all push in, it becomes a "positive sequence", return Stack2 pop.
But think, there is a small optimization, push when not in the Stack1 to restore the anti-sequence, direct push into the stack1, so that in the pop time to determine whether Stack2 is empty, not empty, direct pop, so that the previous "into the queue" pop, and then push Stack1. Added a judgment to simplify the operation of the first stack.
At any time, pop should determine if there are any elements.

  import java.util.Stack; public class Solution {stack<integer> Stack1 = new stack<integer> ();         stack<integer> Stack2 = new stack<integer> ();    public void push (int node) {Stack1.push (node); } public int Pop () {if (Stack1.empty () &&stack2.empty ()) {throw new RuntimeException ("Que        UE is empty! ");}            if (Stack2.empty ()) {while (!stack1.empty ()) {Stack2.push (Stack1.pop ());    }} return Stack2.pop (); }}
import java.util.Stack;class Solution {    Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();    public void push(int node) {        while(!stack2.empty()){            stack1.push(stack2.pop());        }        stack1.push(node);    }    public int pop() {        if(stack1.empty()&&stack2.empty()){            throw new RuntimeException("Queue is empty!");        }        while(!stack1.empty()) {            stack2.push(stack1.pop());        }        return stack2.pop();    }}class Main {}

Then again with my big JS do again, I big JS, each array is a stack, 233, direct push and pop method.
Note that the JS pair pops () when the two stacks are empty processing. JS is the default return undefined, other static languages are generally reported exceptions.

var stack1 = [],    stack2 = [];function push(node) {    stack1.push(node);}function pop() {    if (!stack2.length&&!stack2.length) {        //处理    }    if (!stack2.length) {        while (stack1.length) {            stack2.push(stack1.pop());        }    }    return stack2.pop();}/*// 测试var arr = [];arr.push(1)arr.push(2)arr.push(3)console.log(arr);console.log(arr.pop());*/
Title Description

Moves the first element of an array to the end of the array, which we call the rotation of the array. Enter a rotation of a non-descending sorted array, outputting the smallest element of the rotated array. For example, the array {3,4,5,1,2} is a rotation of {1,2,3,4,5}, and the minimum value of the array is 1. Note: All elements given are greater than 0, and if the array size is 0, return 0.

The

Normal lookup time complexity is N, which is definitely to be found in the optimization. Obviously two points, two points of condition, boundary and judgment is the key. The
sequence is guaranteed to be rotated, and if the length is 2, return directly to the right. We're looking for the boundary value now, and the left side of the non-descending sequence is definitely smaller than the right. Now we are narrowing the boundaries of this boundary.
The middle element is greater than the first element, the middle element is in a sequence from left to only one of the middle elements, at which point the smallest element is behind the middle element.
The intermediate element is less than the first element, the intermediate element is "unhealthy", the left element contains two sequences between the elements, and the smallest number must precede the middle element.
I'm going to keep mid, so I'm sure it's going to be just two numbers left, and the two numbers must be rotated, so the right is the smallest number.
Eg:
3 1 2, return 3 1, because the narrowing is "the length of the rotated Interval"
3 4 1, return 4 1, the final is the smallest right, return.
Another worst case is to have the same element, array[l] = = Array[r] && array[l] = = Array[mid], can not use the conditions to narrow the search interval, this time the sequence must be only two numbers, only order to find, find the first small , you can break directly.

import java.util.ArrayList;public class Solution {    public int minNumberInRotateArray(int [] array) {        int len = array.length;        if(len==0)            return 0;        int l = 0;        int r = len-1;        int mid = 0;        while(r-l!=1) {            mid = (l+r)/2;            if(array[l] == array[r] && array[l] == array[mid]){                return OtherSolve(array,l,r);            }            //当中间比第一个元素大时,最小数在右边,因为右边的最小序列整体都是小于左边的大序列            if(array[mid]>=array[l])                l = mid;            //当中间比第一个元素小时,最小数在左边,最小序列的任何一个数整体都是小于左边的大序列            else if(array[mid]<=array[l]) {                r = mid;            }        }        return array[r];    }     int OtherSolve(int array[],int l,int r){        int t = array[l];        for(int i = l+1; i<=r; i++) {            if(array[i]<t)                t = array[i];        }        return t;    }}

The sword is an offer (five, vi), the queue is implemented with two stacks, the smallest number of the rotated array

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.