• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

cynchanpin

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

power of two

power-of-two


class Solution {
public:
    bool isPowerOfTwo(int n) {
        return n>=1 && !(n&(n-1));
    }
};


n=10000***000, 
<=> n&(n-1)=0


是这种方法的核心

   

https://leetcode.com/discuss/40202/only-push-others-using-queue-combination-shared-solutions

这题有一个好的方法。是用链表实现的队列。来模拟栈,仅仅有push是on, 其它是o1操作的

class MyStack 
{
    Queue<Integer> queue;

    public MyStack()
    {
        this.queue=new LinkedList<Integer>();
    }

    // Push element x onto stack.
    public void push(int x) 
    {
       queue.add(x);
       for(int i=0;i<queue.size()-1;i++)
       {
           queue.add(queue.poll());
       }
    }

    // Removes the element on top of the stack.
    public void pop() 
    {
        queue.poll();
    }

    // Get the top element.
    public int top() 
    {
        return queue.peek();
    }

    // Return whether the stack is empty.
    public boolean empty() 
    {
        return queue.isEmpty();
    }
}
自己写了一个C++版本号,事实上不须要链式栈,发现了这种方法更好的实现了


class Stack {
public:
    // Push element x onto stack.
    void push(int x) {
        q.push(x);
        int qsize=q.size();
        for(int i=0;i<qsize-1;i++){
            q.push(q.front());
            q.pop();
        }
    }

    // Removes the element on top of the stack.
    void pop() {
        q.pop();
    }

    // Get the top element.
    int top() {
        return q.front();
    }

    // Return whether the stack is empty.
    bool empty() {
        return q.empty();
    }
private:
    queue<int> q;
};

记住几个关键的递归式解。能够高速报出答案,免得被主定理,或者plugin 展开计算

T(n)=T(n/2)+O(1) 二分 logn

T(n)=2T(n/2)+O(n) 快排,归并 nlogn

T(n)=2T(n/2)+O(1) n 分治等于没治

posted on 2017-05-27 14:27  cynchanpin  阅读(160)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3