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:

 /**
* 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* constructMaximumBinaryTree(vector<int>& nums) {
return solver(nums, , nums.size() - );
} TreeNode* solver(vector<int>& nums, int left, int right){
if (left > right ) return NULL; int index_max = left;
for(int i = left;i <= right;i++){
if(nums[i] > nums[index_max]) index_max = i;
} TreeNode* root = new TreeNode(nums[index_max]);
root->left = solver(nums, left, index_max - );
root->right = solver(nums, index_max + , right);
return root;
}
};

c++

 # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
root, index_max = TreeNode(max(nums)), nums.index(max(nums))
root.left = self.constructMaximumBinaryTree(nums[:index_max])
root.right = self.constructMaximumBinaryTree(nums[index_max+1:])
return root

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 = ;
while(num>){
sum += num %;
num = num /;
}
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 = , D = , R = , L = ;
for(int i = ; 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 = , , ,
for move in moves:
if move == 'U':
U = U+
if move == 'D':
D = D+
if move == 'R':
R = R+
if move == 'L':
L = L+
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 ) + (t2.val if t2 else ))
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  in decimal

诡异的XOR

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

  1. 2017/11/22 Leetcode 日记

    2017/11/22 Leetcode 日记 136. Single Number Given an array of integers, every element appears twice ex ...

  2. 2017/11/21 Leetcode 日记

    2017/11/21 Leetcode 日记 496. Next Greater Element I You are given two arrays (without duplicates) num ...

  3. 2017/11/13 Leetcode 日记

    2017/11/13 Leetcode 日记 463. Island Perimeter You are given a map in form of a two-dimensional intege ...

  4. 2017/11/20 Leetcode 日记

    2017/11/14 Leetcode 日记 442. Find All Duplicates in an Array Given an array of integers, 1 ≤ a[i] ≤ n ...

  5. 2017/11/9 Leetcode 日记

    2017/11/9 Leetcode 日记 566. Reshape the Matrix In MATLAB, there is a very useful function called 'res ...

  6. 2017/11/7 Leetcode 日记

    2017/11/7 Leetcode 日记 669. Trim a Binary Search Tree Given a binary search tree and the lowest and h ...

  7. 2017/11/6 Leetcode 日记

    2017/11/6 Leetcode 日记 344. Reverse String Write a function that takes a string as input and returns ...

  8. 2017/11/5 Leetcode 日记

    2017/11/5 Leetcode 日记 476. Number Complement Given a positive integer, output its complement number. ...

  9. jingchi.ai 2017.11.25-26 Onsite面试

    时间:2017.11.25 - 11.26 地点:安徽安庆 来回路费报销,住宿报销. day1: 大哥哥问了我一个实际中他们遇到的问题.有n个点,将点进行分块输出,输出各个块的均值点.具体就是100* ...

随机推荐

  1. linux中操作数据库的使用命令记录

    1,mysql 查看数据库表编码格式: show create table widget; 修改数据库表编码格式: alter table widget default character set u ...

  2. javascript小技巧之with()方法

    With()方法平时用得不多,本文用个小例子来学习一下.在这里记录.个人感觉还是很方便的. 有了 With 语句,在存取对象属性和方法时就不用重复指定参考对象,在 With 语句块中,凡是 JavaS ...

  3. JavaScript数据类型和转换

    JavaScript数据类型 1.Boolean(布尔) 布尔:(值类型)var b1=true;//布尔类型 2.Number(数字) 数值:(值类型)var n1=3.1415926;//数值类型 ...

  4. laravel中form表单,ajax传值没反应

    laravel中form表单,ajax传值没反应时,可能是令牌有问题. form中添加: {{csrf_token()}} ajax中添加: data: {'page': page, '_token' ...

  5. 伪ajax操作

    什么是伪Ajax操作? 说白了就是假的ajax操作,但是它和正常的ajax操作的目的是一样的,把前端的信息发送到后台 先看一下代码吧! ajax.html <form action=" ...

  6. MSSQL 详解SQL Server连接(内连接、外连接、交叉连接)

    在查询多个表时,我们经常会用“连接查询”.连接是关系数据库模型的主要特点,也是它区别于其它类型数据库管理系统的一个标志. 什么是连接查询呢? 概念:根据两个表或多个表的列之间的关系,从这些表中查询数据 ...

  7. JDK1.8新特性

    1.Lambda                                                            Lambda的语法目前仅对于只有一个抽象方法的接口. 在Lamb ...

  8. MySQL之——如何添加新数据库到MySQL主从复制列表 【转】

    转自 转载请注明出处:http://blog.csdn.net/l1028386804/article/details/54653691 MySQL主从复制一般情况下我们会设置需要同步的数据库,使用参 ...

  9. Minimum Palindromic Factorization(最少回文串分割)

    Minimum Palindromic Factorization(最少回文串分割) 以下内容大部分(可以说除了关于回文树的部分)来自论文A Subquadratic Algorithm for Mi ...

  10. 用于启动 Windows Phone 8 内置应用的 URI 方案

    本主题列出了可用于启动内置应用的 URI 方案.许多内置于 Windows Phone 的应用,都可以通过调用 LaunchUriAsync(Uri) 和传入一个使用与要启动应用相关的方案的 URI, ...