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:
- The root is the maximum number in the array.(根节点是数组中的最大值)
- The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.(左子树是左子数组构造出的最大子树)
- 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 ≤ x, y < 231.
Solutions:
class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
Java一行
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 日记的更多相关文章
- 2017/11/22 Leetcode 日记
2017/11/22 Leetcode 日记 136. Single Number Given an array of integers, every element appears twice ex ...
- 2017/11/21 Leetcode 日记
2017/11/21 Leetcode 日记 496. Next Greater Element I You are given two arrays (without duplicates) num ...
- 2017/11/13 Leetcode 日记
2017/11/13 Leetcode 日记 463. Island Perimeter You are given a map in form of a two-dimensional intege ...
- 2017/11/20 Leetcode 日记
2017/11/14 Leetcode 日记 442. Find All Duplicates in an Array Given an array of integers, 1 ≤ a[i] ≤ n ...
- 2017/11/9 Leetcode 日记
2017/11/9 Leetcode 日记 566. Reshape the Matrix In MATLAB, there is a very useful function called 'res ...
- 2017/11/7 Leetcode 日记
2017/11/7 Leetcode 日记 669. Trim a Binary Search Tree Given a binary search tree and the lowest and h ...
- 2017/11/6 Leetcode 日记
2017/11/6 Leetcode 日记 344. Reverse String Write a function that takes a string as input and returns ...
- 2017/11/5 Leetcode 日记
2017/11/5 Leetcode 日记 476. Number Complement Given a positive integer, output its complement number. ...
- jingchi.ai 2017.11.25-26 Onsite面试
时间:2017.11.25 - 11.26 地点:安徽安庆 来回路费报销,住宿报销. day1: 大哥哥问了我一个实际中他们遇到的问题.有n个点,将点进行分块输出,输出各个块的均值点.具体就是100* ...
随机推荐
- 字符串hash的学习部分 可以算是模板?
资料来自于http://www.bilibili.com/video/av7230433/ 定义这个字符串为s ①单hash hash[i] = (hash[i - 1] * p + idx(s[i] ...
- HDU 3977 斐波那契循环节
这类型的题目其实没什么意思..知道怎么做后,就有固定套路了..而且感觉这东西要出的很难的话,有这种方法解常数会比较大吧..所以一般最多套一些比较简单的直接可以暴力求循环节的题目了.. /** @Dat ...
- 在GitHub搭建个人博客 地址: https://douzujun.github.io/
搭建博客地址:https://douzujun.github.io/ 博客模板:https://github.com/douzujun/douzujun.github.io 显示效果:
- HTML入门(一)
---恢复内容开始--- HTML 一 .HTML介绍 1. 什么是HTML? 超文本标记语言: 超文本: 比普通文本更强大 标记语言: 使用一组标签对内容进行描述的一门语言,它不是编程语言! 2. ...
- Python学习笔记(四十三)virtualenv (创建一套“隔离”的Python运行环境)
摘抄自:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432712108 ...
- Java实现线性表-顺序表示和链式表示
顺序表示和链式表示的比较: 1.读写方式:顺序表可以顺序存取,也可以随机存取:链表只能从表头顺序存取元素: 2.逻辑结构与物理结构:顺序存储时,逻辑上相邻的元素其对应的物理存储位置也相邻:链式存储时, ...
- 接口自动化测试框架HttpRunner
接口自动化测试框架 https://github.com/HttpRunner/HttpRunner http://debugtalk.com/post/ApiTestEngine-api-test- ...
- 【洛谷 P3199】 [HNOI2009]最小圈(分数规划,Spfa)
题目链接 一开始不理解为什么不能直接用\(Tarjan\)跑出换直接求出最小值,然后想到了"简单环",恍然大悟. 二分答案,把所有边都减去\(mid\),判是否存在负环,存在就\( ...
- react input 设置默认值
1.text类型 <input type="text" value={默认值} /> ,这种写法可以显示默认值,但不能对输入框进行编辑 正确写法: <input ...
- bzoj 2303 并查集
首先如果没有限制的话,我们可以直接求出答案,假设对于n*m的矩阵,我们最上方一行和左方的一列随意确定,那么首先这写确定的状态肯定是不会不合法的,因为我们可以调整剩下的01状态来使得这一行一列的状态合法 ...