• leetcode 中等题(2)


    50. Pow(x, n) (中等)

        double myPow(double x, int n) {
            double ans = 1;
            unsigned long long p;
            if (n < 0) {
                p = -n;
                x = 1 / x;
            } else {
                p = n;
            }
            while (p) {
                if (p & 1)
                    ans *= x;
                x *= x;
                p >>= 1;
            }
            return ans;
        }

     96. Unique Binary Search Trees(很快)

    1 class Solution {
    2 public:
    3     int numTrees(int n) {
    4         long ans=1;
    5         for(int i=n+1;i<=2*n;i++)
    6             ans = i*ans/(i-n);
    7         return ans/(n+1);
    8     }
    9 };
    View Code

     94. Binary Tree Inorder Traversal(很快)

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<int> inorderTraversal(TreeNode* root) {
    13         stack<TreeNode*> s;
    14         vector<int> res;
    15         if(root==NULL) return res;
    16         TreeNode* p=root;
    17         while(!s.empty()||p){
    18             if(p){
    19                 s.push(p);
    20                 p=p->left;
    21             }
    22             else{
    23                 p=s.top();
    24                 s.pop();
    25                 res.push_back(p->val);
    26                 p=p->right;
    27             }
    28         }
    29         return res;
    30     }
    31 };
    View Code
     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<int> res;
    13     vector<int> inorderTraversal(TreeNode* root) {
    14         if(!root) return  res;
    15         inorderTraversal(root->left);
    16         res.push_back(root->val);
    17         inorderTraversal(root->right);
    18         return res;
    19     }
    20 };
    View Code
     89. Gray Code(很快)
     1 class Solution {
     2 public:
     3     vector<int> grayCode(int n) {
     4         int  len = 1 << n;
     5         vector<int> res(len,0);
     6         for(int i = 0;i != len;++i){
     7             res[i] =i ^ (i >> 1); 
     8         }
     9         return res;
    10     }
    11 };
    View Code
    所有博文均为原著,如若转载,请注明出处!
  • 相关阅读:
    MySQL中的事务
    MySQL中的锁
    MySQL查询更新所有满足条件的数据
    MySQL存储引擎
    MySQL架构
    MySQL中存储json格式数据
    Java反射破坏单例模式
    合唱队(华为OJ)
    Java实现生产者消费者问题
    Spring IOC + AOP 的实现
  • 原文地址:https://www.cnblogs.com/zpcoding/p/10205578.html
Copyright © 2020-2023  润新知