2017/11/3 Leetcode 日记

654. Maximum Binary Tree

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.(根节点是数组中的最大值)
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.(左子树是左子数组构造出的最大子树)
  3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.(右子树是右子数组构造出的最大子树)

Solutions:

 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     TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
13         return solver(nums, 0, nums.size() - 1);
14     }
15
16     TreeNode* solver(vector<int>& nums, int left, int right){
17         if (left > right ) return NULL;
18
19         int index_max = left;
20         for(int i = left;i <= right;i++){
21             if(nums[i] > nums[index_max]) index_max = i;
22         }
23
24         TreeNode* root = new TreeNode(nums[index_max]);
25         root->left = solver(nums, left, index_max - 1);
26         root->right = solver(nums, index_max + 1, right);
27         return root;
28     }
29 };

c++

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7
 8 class Solution(object):
 9     def constructMaximumBinaryTree(self, nums):
10         """
11         :type nums: List[int]
12         :rtype: TreeNode
13         """
14         if not nums:
15             return None
16         root, index_max = TreeNode(max(nums)), nums.index(max(nums))
17         root.left = self.constructMaximumBinaryTree(nums[:index_max])
18         root.right = self.constructMaximumBinaryTree(nums[index_max+1:])
19         return root
20         

python

461. Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

(两个数,求异或后的数二进制中1的数量)

Note:
  0 ≤ xy < 231.

Solutions:

class Solution {
    public int hammingDistance(int x, int y) {
        return Integer.bitCount(x ^ y);
    }
}

Java一行

python3一行

class Solution {
public:
    int hammingDistance(int x, int y) {
        return count(x^y);
    }
    int count(int num){
        int sum = 0;
        while(num>0){
            sum += num %2;
            num = num /2;
        }
        return sum;
    }
};

c++

657. Judge Route Circle

Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.

The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L(Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.

(判断机器人是否走了一个圈,其实就是判断字串R=L, U=D)

Solutions:

class Solution {
public:
    bool judgeCircle(string moves) {
        int U = 0, D = 0, R = 0, L = 0;
        for(int i = 0; i < moves.size(); i++){
            switch(moves[i]){
                case ‘U‘:
                    U++;
                    break;
                case ‘D‘:
                    D++;
                    break;
                case ‘R‘:
                    R++;
                    break;
                case ‘L‘:
                    L++;
                    break;
            }
        }
        if((U==D) && (R==L)) return true;
        return false;
    }
};

c++

class Solution:
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        U,D,L,R = 0, 0, 0, 0
        for move in moves:
            if move == ‘U‘:
                U = U+1
            if move == ‘D‘:
                D = D+1
            if move == ‘R‘:
                R = R+1
            if move == ‘L‘:
                L = L+1
        if U == D and R == L:
            return True
        return False

python3

617. Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

(如题)

Solutions:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if(t1 == NULL && t2 == NULL) return NULL;
        if(t1 == NULL && t2 != NULL) return t2;
        if(t1 != NULL && t2 == NULL) return t1;

        TreeNode* root = new TreeNode(t1->val + t2->val);
        root->left = mergeTrees(t1->left, t2->left);
        root->right = mergeTrees(t1->right, t2->right);
        return root;
    }
};

c++

class Solution:
    def mergeTrees(self, t1, t2):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        if not t1 and not t2: return None
        root = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0))
        root.left = self.mergeTrees(t1 and t1.left, t2 and t2.left)
        root.right = self.mergeTrees(t1 and t1.right, t2 and t2.right)
        return root

how does "and" work?
"""
I am using t1 and t1.left as a shortcut for t1.left if t1 is not None else None.

Here, "x and y" evaluates as follows: If x is truthy, then the expression evaluates as y. Otherwise, it evaluates as x.

When t1 is None, then None is falsy, and t1 and t1.left evaluates as t1 which is None.

When t1 is not None, then t1 is truthy, and t1 and t1.left evaluates as t1.left as desired.

This is a standard type of idiom similar to the "?" operator in other languages. I want t1.left if t1 exists, otherwise nothing.

Alternatively, I could use a more formal getattr operator: getattr(t1, ‘left‘, None)
"""

python3

627. Swap Salary

Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table.

(更换性别)

Solutions:

update salary set sex = (CASE WHEN sex = ‘m‘
                        THEN ‘f‘
                        ELSE ‘m‘
                        END)

简单版

update salary set sex = CHAR(ASCII(‘f‘) ^ ASCII(‘m‘) ^ ASCII(sex));

in ascii table, ‘f‘ is 0x66, ‘m‘ is 0x6D, and 0x66 xor 0x6D = 0x0B, which is 11 in decimal

诡异的XOR

时间: 2024-10-09 01:24:18

2017/11/3 Leetcode 日记的相关文章

2017/11/07_那么明显的坑你还往里跳 Cannot set property &#39;innerHTML&#39; of null

学习react,使用webpack构建工具 在html引入生成的bundle.js时,写成了这样子: 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <script src="bundle.js"></scri

2017.11.15 String、StringBuffer、StringBuilder的比较

参考来自:http://blog.csdn.net/jeffleo/article/details/52194433 1.速度 一般来说,三者的速度是:StringBuilder > StringBuffer > String. 但是,在String a = "how" + "old" + "are" + "you".这种直接拼接的情况下,String速度最高.这是因为jvm的优化问题,jvm会自动识别,把&quo

2017.11.11 B201 练习题思路及解题方法

2017.11.11 B201 练习题思路及解题方法 题目类型及涵盖知识点 本次总共有6道题目,都属于MISC分类的题目,涵盖的知识点有 信息隐藏 暴力破解 音轨,摩斯电码 gif修改,base64原理 序列密码 各题的解题思路及过程 签到题:隐写诶.jpeg[知识点:信息隐藏] 本题为 隐写诶.jpeg 的图片文件,可以对该文件尝试一些基本的图片隐写解题思路,如将文件后缀名由 .jpeg 更改为 .txt 后利用记事本打开,或直接对文件点击右键后 打开方式→记事本打开,在打开的记事本窗口中获得

2017.11.25【NOIP提高组】模拟赛A组

2017.11.25[NOIP提高组]模拟赛A组 T1 3467. [NOIP2013模拟联考7]最长上升子序列(lis) T2 3468. [NOIP2013模拟联考7]OSU!(osu) T3 3472. [NOIP2013模拟联考8]匹配(match) T1 有转移方程f[i]=max{f[j]}+1,a[j]<a[i] 可以用线段树+离散化维护这个方程,因为涉及以往状态可以用主席树维护 打太丑爆空间了 Code 1 #include<cstdio> 2 #include<c

[LOJ 6249]「CodePlus 2017 11 月赛」汀博尔

Description 有 n 棵树,初始时每棵树的高度为 H_i,第 i 棵树每月都会长高 A_i.现在有个木料长度总量为 S 的订单,客户要求每块木料的长度不能小于 L,而且木料必须是整棵树(即不能为树的一部分).现在问你最少需要等多少个月才能满足订单. Input 第一行 3 个用空格隔开的非负整数 n,S,L,表示树的数量.订单总量和单块木料长度限制.第二行 n 个用空格隔开的非负整数,依次为 H1,H2,…,Hn.第三行 n 个用空格隔开的非负整数,依次为 A1,A2,…,An. Ou

51CTO学院新课发布~~带你遇见更好的自己(六)(2017.11.20-11.26)

 一周的时间匆匆即逝,又到了给你们出新课列表的时候了,小编每周都辛苦的给你们推课,也不几道你们到底看了没,想到小编之前做讲师的时候,那可是一把鼻涕一把泪的催着同学们学习. 有个段子特别能描述当时的心情:"老师这个职业吧,说的文明点就是每天带着学生在知识的海洋里畅游.然而畅游一段时间吧,你会发现:只有你一个人上岸了!!!!!!!然后你还得返回,一个一个去捞.有些吧,昨天捞上来今天又掉下去了还得捞.在你喘息的时候,你会惊恐地发现:还有往回游的".So,跟我一起游往这周的新课列表吧,锵锵锵~

51CTO学院新课发布~~带你遇见更好的自己(七)(2017.11.27-12.03)

以往新课发布的开场白,都是小编姐姐逗比的闲扯,小编姐姐准备转变一下画风,以后的新课发布开场白就谈谈每周我对于职场或者生活的一点小理解吧. 上周看到一篇文章,关于人和人的身价的差距:职场10年,为什么有人已经当上了董事总经理,而有的人还是资深销售经理?为什么有人已经当上了架构师,而有的人还是资深技术人员?为什么有人已经身价数十亿美金,而有的人还在为竞争总监头衔而周游于人情场?人和人的身价几倍甚至几十倍的差距,真的就只是智商.教育背景.能力.勤奋程度所决定的吗?当然不是.更大程度上是由个人的价值观.

51CTO学院新课发布~~带你遇见更好的自己(九)(2017.11.04-12.17)

新的一周新的失望,大家好,你们的毒鸡汤姐又华丽丽的上线了.今天想跟大家聊聊这个投资.为什么要说这个呢?因为最近小编的妈妈(一位三四线小城市的中年妇女),居然开始玩区域链了,这使得小编不寒而栗,毕竟我现在都没彻底搞清楚区域链.曾记得我是2014年的时候开始听说比特币,身边有买比特币的朋友也一直跟我分享他们的喜悦.因为今年比特币的大幅上涨,形成了一种投资热潮.随之而来的区域链.加密货币等等获得了更多投资者的关注.不少投资者开始寻找下一个比特币,于2011年推出的莱特币或许是其中一个备选.曾经莱特币在

LeetCode日记3

(2015/11/3) LeetCode-36 Valid Sudoku:(easy) 1)使用数据结构 set<char> emptyset; vector<set<char>> mp(27, emptyset); 2)下标0-8存储行中的数字,9-17存储列中的数字,18-26存储3×3块中数字. 3)双重for循环中,i表示行,9 + j表示列,18 + i / 3 + 3 * (j / 3)表示块. (2015/11/12) LeetCode-38 Count