• 2017/11/3 Leetcode 日记


    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
  • 相关阅读:
    关于键盘事件对象code值
    解决父元素定位后宽度不随着子元素增大而增大的问题
    绝对定位后元素的宽高如果用百分比表示的计算方法
    4.7做作业时发现,内联元素设置宽高背景以后正常不显示,但是设置了position:absolute;以后就可以显示了。起到了和display:block;一样的效果。然后查了一下知道了。
    react-native中显示本地照片或视频
    用js实现div元素的拖拽、
    TCP协议浅谈
    TCP的三次握手和四次挥手
    TCP协议
    关于this指向的一点小分享
  • 原文地址:https://www.cnblogs.com/yoyo-sincerely/p/7779428.html
Copyright © 2020-2023  润新知