Leetcode 232 Implement Queue using Stacks 和 231 Power of Two,leetcodestacks

來源:互聯網
上載者:User

Leetcode 232 Implement Queue using Stacks 和 231 Power of Two,leetcodestacks
1. 232 Implement Queue using Stacks1.1 問題描述

  使用棧類比實現隊列。類比實現如下操作:
  

  • push(x). 將元素x放入隊尾。
  • pop(). 移除隊首元素。
  • peek(). 擷取隊首元素。
  • empty(). 判斷隊列是否為空白。

注意:只能使用棧的標準操作,push,pop,size和empty函數。

1.2 方法與思路

   本題和用隊列實現棧思路一樣,設兩個輔助棧stk1和stk2。
   push(x): 將x入棧stk1.
   pop(): 依次將stk1中的元素pop到stk2中,只留最後一個pop掉,然後再將stk2中的元素pop到stk1中。
   peek(): 和pop操作類似,只不過最後一個元素不是pop,而是取值返回。
   empty(): 直接判斷stk1是否為空白即可。

class Queue {    stack<int> stk1,stk2;public:    // Push element x to the back of queue.    void push(int x) {        stk1.push(x);    }    // Removes the element from in front of queue.    void pop(void) {        while(stk1.size() > 1)        {            stk2.push(stk1.top());            stk1.pop();        }        if(stk1.size() == 1)            stk1.pop();        while(!stk2.empty())            stk1.push(stk2.top()),stk2.pop();    }    // Get the front element.    int peek(void) {        int re;        while(stk1.size() > 1)        {            stk2.push(stk1.top());            stk1.pop();        }        if(stk1.size() == 1)            re = stk1.top();        while(!stk2.empty())            stk1.push(stk2.top()),stk2.pop();        return re;    }    // Return whether the queue is empty.    bool empty(void) {        return stk1.empty();    }};
2. 231 Power of Two2.1 問題描述

  判斷一個整數是不是2的冪次方。

2.2 思路與方法

  超簡單的題目,題目給出的n最大為int的最大值,那麼只需要遍曆i從1到30依次計算2的i次方是不是數n即可。
  

class Solution {public:    bool isPowerOfTwo(int n) {        for(int i=0; i < 31; i++)        {            if(pow(2,(double)i) == n) return true;        }        return false;    }};

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.