LeetCode Weekly Contest 6
leetcode现在每周末举办比赛,这是今天上午参加的比赛的题解。
题目难度不算大,两个easy,一个medium,一个hard。hard题之前接触过,所以做得比较顺利。
1. Sum of Left Leaves(Leetcode 404 Easy)
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
分析:比较简单的二叉树问题。二叉树问题大部分用递归就能解决,本题就是traverse的变形,这里加一个flag判断是左子树还是右子树即可。
代码:
/**
* 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 {
private:
int result = ;
void traverse(TreeNode* root, int flag) {
if (root == nullptr) {
return;
}
if (root -> left == nullptr && root -> right == nullptr && flag == -) {
result += root -> val;
return;
}
traverse(root -> left, -);
traverse(root -> right, ); }
public:
int sumOfLeftLeaves(TreeNode* root) {
traverse(root, );
return result;
}
};
2. Convert a Number to Hexadecimal (Leetcode 405 Easy)
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
- All letters in hexadecimal (
a-f
) must be in lowercase. - The hexadecimal string must not contain extra leading
0
s. If the number is zero, it is represented by a single zero character'0'
; otherwise, the first character in the hexadecimal string will not be the zero character. - The given number is guaranteed to fit within the range of a 32-bit signed integer.
- You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:
26 Output:
"1a"
Example 2:
Input:
-1 Output:
"ffffffff"
分析:十六进制的转换,搞清楚负数补码的原理就可以(拿0x100000000 + x即可),注意存的时候用一下long long防止整数溢出。
代码:
class Solution {
public:
string toHex(int num) {
string result;
long long num2 = num;
char hex[] = {'','','','','','','','','','','a','b','c','d','e','f'};
if (num2 < ) {
num2 = 0x100000000 + num2;
}
if (num2 == ) {
result += '';
return result;
}
while (num2 != ) {
result = hex[num2 % ] + result;
num2 /= ;
}
return result;
}
};
3. Queue Reconstruction by Height (LeetCode406 Medium)
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k)
, where h
is the height of the person and k
is the number of people in front of this person who have a height greater than or equal to h
. Write an algorithm to reconstruct the queue.
Note:
The number of people is less than 1,100.
Example
Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
分析:题意是给出人的高度和该高度前面有多少个人,重拍序列满足这一要求。
把序列中的人按照高度从高到低排序,高度一样的前面人越少的越靠前。这样以此处理每一个点,
按照people[i].second中存的有几个比他高来判断他应该在第几个位置插入(比该点高的点已经都进入序列了),处理完毕后即满足要求。
代码:(比较函数用了C++11中的lambda表达式)
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int, int>> result;
sort(people.begin(), people.end(), [](const pair<int, int>& p1, const pair<int, int>& p2)
{
if (p1.first == p2.first) {
return p1.second < p2.second;
}
else return p1.first > p2.first;
} );
for (int i = ; i < people.size(); ++i) {
result.insert(result.begin() + people[i].second, people[i]);
}
return result;
}
};
4. Trapping Rain Water II (Leetcode 407 Hard)
Given an m x n
matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.
Note:
Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000.
Example:
Given the following 3x6 height map:
[
[1,4,3,1,3,2],
[3,2,1,3,2,4],
[2,3,3,2,3,1]
] Return 4.
The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
before the rain.
After the rain, water are trapped between the blocks. The total volume of water trapped is 4.
分析:
维护一个最小堆和一个记录访问与否的数组flag[m][n], 把图中外层一圈元素存入堆中,flag相应标记。
然后开始如下循环:
拿出其中堆顶元素(temp),BFS的方法查看其四周的四个点,
如果存在高度比temp低的点(heightMap[nx][ny]),则temp.h - heightMap[nx][ny]这段高度肯定可以储水。
然后把nx,ny位置的点加入堆中(但其高度应改为temp.h,多出部分已经储水记录过),并更新flag。
对于高度比temp高的点,直接加入堆中,并更新flag即可。
这样当堆中为空处理完所有点后,结果即为储水的值。
代码:
class Solution {
private:
struct node {
int x, y, h;
node(int nx, int ny, int nh):x(nx), y(ny), h(nh){}
};
int dx[] = {-,,,};
int dy[] = {,,-,};
struct cmp {
bool operator() (const node &n1, const node &n2) {
return n1.h > n2.h;
}
};
public:
int trapRainWater(vector<vector<int>>& heightMap) {
if (heightMap.size() == ) {
return ;
}
int m = heightMap.size(), n = heightMap[].size();
int flag[m][n] = {};
int result = ;
priority_queue<node, vector<node>, cmp> que;
for (int i = ; i < m; ++i) {
que.push(node(i,, heightMap[i][]));
flag[i][] = ;
que.push(node(i,n - , heightMap[i][n - ]));
flag[i][n - ] = ;
}
for (int i = ; i < n - ; ++i) {
que.push(node(,i,heightMap[][i]));
flag[][i] = ;
que.push(node(m - , i,heightMap[m - ][i]));
flag[m - ][i] = ;
}
while (!que.empty()) {
node temp = que.top();
que.pop();
for (int i = ; i < ; ++i) {
int nx = temp.x + dx[i], ny = temp.y + dy[i];
if (nx >= && nx < m && ny >= && ny < n && !flag[nx][ny]) {
result += max(, temp.h - heightMap[nx][ny]);
que.push(node(nx, ny, max(temp.h, heightMap[nx][ny])) );
flag[nx][ny] = ;
}
}
}
return result;
}
};
LeetCode Weekly Contest 6的更多相关文章
- LeetCode Weekly Contest 8
LeetCode Weekly Contest 8 415. Add Strings User Accepted: 765 User Tried: 822 Total Accepted: 789 To ...
- leetcode weekly contest 43
leetcode weekly contest 43 leetcode649. Dota2 Senate leetcode649.Dota2 Senate 思路: 模拟规则round by round ...
- LeetCode Weekly Contest 23
LeetCode Weekly Contest 23 1. Reverse String II Given a string and an integer k, you need to reverse ...
- Leetcode Weekly Contest 86
Weekly Contest 86 A:840. 矩阵中的幻方 3 x 3 的幻方是一个填充有从 1 到 9 的不同数字的 3 x 3 矩阵,其中每行,每列以及两条对角线上的各数之和都相等. 给定一个 ...
- LeetCode Weekly Contest
链接:https://leetcode.com/contest/leetcode-weekly-contest-33/ A.Longest Harmonious Subsequence 思路:hash ...
- 【LeetCode Weekly Contest 26 Q4】Split Array with Equal Sum
[题目链接]:https://leetcode.com/contest/leetcode-weekly-contest-26/problems/split-array-with-equal-sum/ ...
- 【LeetCode Weekly Contest 26 Q3】Friend Circles
[题目链接]:https://leetcode.com/contest/leetcode-weekly-contest-26/problems/friend-circles/ [题意] 告诉你任意两个 ...
- 【LeetCode Weekly Contest 26 Q2】Longest Uncommon Subsequence II
[题目链接]:https://leetcode.com/contest/leetcode-weekly-contest-26/problems/longest-uncommon-subsequence ...
- 【LeetCode Weekly Contest 26 Q1】Longest Uncommon Subsequence I
[题目链接]:https://leetcode.com/contest/leetcode-weekly-contest-26/problems/longest-uncommon-subsequence ...
- LeetCode Weekly Contest 47
闲着无聊参加了这个比赛,我刚加入战场的时候时间已经过了三分多钟,这个时候已经有20多个大佬做出了4分题,我一脸懵逼地打开第一道题 665. Non-decreasing Array My Submis ...
随机推荐
- JavaScript创建对象的几种方式总结
ECMA把对象定义为:无序属性的集合,其属性可以包含基本值.对象或者函数. 1. 使用Object构造函数创建对象 创建自定义对象的最简单的方式就是创建一个Object的实例,然后再为它添加属性和方法 ...
- python中os模块简介
一.什么是os模块 os模块提供了多数操作系统的功能接口函数.当os模块被导入后,它会自适应于不同的操作系统平台,根据不同的平台进行相应的操作,在python编程时,经常和文件.目录打交道,所以离不了 ...
- 学习Python笔记---列表简介
列表: 列表由一系列按特定顺序排列的元素组成.你可以创建包涵字母表中所有字母.数字0-9或所有家庭成员姓名的列表:也可以将任何东西加入列表中,其中的元素之间可以没有任何关系. 列表 在Python中, ...
- Python实例 遍历文件夹和文件
import os import os.path # os,os.path里包含大多数文件访问的函数,所以要先引入它们. # 请按照你的实际情况修改这个路径 rootdir = &quo ...
- Data Lake Analytics IP白名单设置攻略
当我们成功开通了 DLA 服务之后,第一个最想要做的事情就是登录 DLA 数据库.而登录数据库就需要一个连接串.下面这个页面是我们首次开通 DLA 之后的界面,在这里我们要创建一个服务访问点. 在上面 ...
- c++ 进制转换函数
转自:https://blog.csdn.net/wangjunchengno2/article/details/78690248 strtol 函数: 它的功能是将一个任意1-36进制数转化为10进 ...
- PHP 学习1.4
1.session and cookie 示列: <?phpsession_start();?><!DOCTYPE html PUBLIC "-//W3C//DTD XHT ...
- bzoj2467 生成树
传送门 生成树计数裸题,因为模数不是质数所以要用辗转相除的高斯消元. de了很久的bug然后发现一个变量A赋值后下一行又申明了一个新的临时变量A(: //Achen #include<algor ...
- 词袋和 TF-IDF 模型
做文本分类等问题的时,需要从大量语料中提取特征,并将这些文本特征变换为数值特征.常用的有词袋模型和TF-IDF 模型 1.词袋模型 词袋模型是最原始的一类特征集,忽略掉了文本的语法和语序,用一组无序的 ...
- LintCode_175 翻转二叉树
题目 翻转一棵二叉树 您在真实的面试中是否遇到过这个题? Yes 样例 1 1 / \ / \ 2 3 => 3 2 / \ 4 4 和前序遍历代码很相似从叶子节点依次翻转递归到根节点C++代码 ...