Leetcode 记录(101~200)
Now, I want to just use English to explain the problem, it's about two month before the interview, so I have to practice my oral English more.
And I will write my explainations in my code in order to keep this passage looking comfortable.
101. Symmetric Tree
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/ /*
I think it's a easy problem if you just works the problem one after another, but you probably don't know how to solve it with iterative way even if you have already solve it by recursive manner. You may think why should I use another way? However, the recursive way may be easy to understand, but it will cost more time at the same time and the stack can overflow. So it necessary to understand how to solve this problem iteratively. First,we can image a line which is inseted between the left child and right child, the line is the mirror, every node can see a totally same node from this mirror. So we fold this tree and check. Actually, if we reverse one of the child tree and compare it with another, you can do it as same as tree-folding.
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL) return true;
queue<TreeNode*> node1,node2;
TreeNode* now1,*now2;
node1.push(root->left);
node2.push(root->right);
while(!node1.empty()&&!node2.empty()){
now1=node1.front();
node1.pop();
now2=node2.front();
node2.pop();
if (NULL==now1&&NULL==now2)
continue;
if (NULL==now1||NULL==now2)
return false;
if(now1->val!=now2->val){
return false;
}
node1.push(now1->left);
node1.push(now1->right);
node2.push(now2->right);
node2.push(now2->left);
}
return true;
}
};
105. Construct Binary Tree from Preorder and Inorder Traversal,Given preorder and inorder traversal of a tree, construct the binary tree.
It's a good problem and it's worth writing it again.
114. Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place. I try to use recusive way to solve it, but I think it's too complex. Maybe I should write it a few days later.
115.It's truely a good problem. Though the difficulty is hard, you can easily do it when you understand what is dynamic programming. The first of discussion have a good explanation, and maybe you should explan this problem like that.
123.good problem
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. When you simplify this problem, you will find that you need to find two maxmium continuous subsequence in the array which is formed by the difference between the adjacent price. You can set an i which means the boundary of these two subsequence.
class Solution {
public:
int maxProfit(vector<int>& prices) {
int Max1=,Max2=;
int ans=;
int n=prices.size();
vector<int> f1(n,);
vector<int> f2(n,);
for(int i=;i<n;i++){
int dis=prices[i]-prices[i-];
if(Max2<){
Max2=dis;
}
else Max2+=dis;
Max1=max(Max2,Max1);
f1[i]=Max1;
}
Max1=,Max2=;
for(int i=n-;i>=;i--){
int dis=prices[i]-prices[i+];
if(Max2>){
Max2=dis;
}
else Max2+=dis;
Max1=min(Max2,Max1);
f2[i]=Max1;
ans=max(ans,f1[i]-f2[i]);
}
return ans;
}
};
128.
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2]
,
The longest consecutive elements sequence is [1, 2, 3, 4]
. Return its length: 4
.
Your algorithm should run in O(n) complexity.
unorder_map is faster than map, but it will cost more memory.
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int,int> mp;
int tot=;
int ans=;
for(int i=;i<nums.size();i++){
if(!mp[nums[i]]) mp[nums[i]]=tot++;
}
for(int i=;i<nums.size();i++){
if(!mp[nums[i]]) continue;
int f1=nums[i]-,f2=nums[i]+;
while(mp[f1]) mp[f1]=,f1--;
while(mp[f2]) mp[f2]=,f2++;
ans=max(ans,f2-f1-);
}
return ans;
}
};
130
stackoverflow if you use dfs???????
class Solution {
public:
int n,m;
struct Node{
int x,y;
};
int d[][]={,,,,,-,-,};
void bfs(int x,int y,vector<vector<char>>& board,vector<vector<int>>& vis){
vis[x][y]=;
queue<Node> q;
Node now,next;
now.x=x,now.y=y;
q.push(now);
while(!q.empty()){
now=q.front();
q.pop();
for(int i=;i<;i++){
next.x=now.x+d[i][];
next.y=now.y+d[i][];
if(next.x>=&next.x<n&&next.y>=&&next.y<m&&!vis[next.x][next.y]&&board[next.x][next.y]=='O'){
q.push(next);
vis[next.x][next.y]=;
}
}
}
}
void solve(vector<vector<char>>& board) {
if(board.size()==||board[].size()==) return;
n=board.size(),m=board[].size();
vector<vector<int>> vis(n,vector<int>(m,));
for(int j=;j<m;j++){
if(!vis[][j]&&board[][j]=='O') bfs(,j,board,vis);
if(!vis[n-][j]&&board[n-][j]=='O') bfs(n-,j,board,vis);
}
for(int j=;j<n;j++){
if(!vis[j][]&&board[j][]=='O') bfs(j,,board,vis);
if(!vis[j][m-]&&board[j][m-]=='O') bfs(j,m-,board,vis);
}
for(int i=;i<n;i++){
for(int j=;j<m;j++){
if(!vis[i][j]&&board[i][j]=='O') board[i][j]='X';
}
}
}
};
132 大概意思就是判断最少有多少回文串
class Solution {
public:
int minCut(string s) {
int len=s.length();
vector< vector<int> > dp(len+,vector<int>(len+,));
vector<int> sum(len,);
for(int i=;i<len;i++){
sum[i]=;
for(int j=;j<=i;j++){
if(s[i]==s[j]&&dp[j+][i-]==){
dp[j][i]=;
if(j==) sum[i]=;
else if(j->=){
sum[i]=min(sum[i],sum[j-]+);
}
}
else dp[j][i]=;
}
}
return sum[len-];
}
};
133 复制一幅图,作节点到节点的映射,防止环的情况
141,142判断链表中是否包含环,可以用map存,也可以用快慢指针,需要能流利的解释
/*
my solution is like this: using two pointers, one of them one step at a time. another pointer each take two steps. Suppose the first meet at step k,the length of the Cycle is r. so..2k-k=nr,k=nr
Now, the distance between the start node of list and the start node of cycle is s. the distance between the start of list and the first meeting node is k(the pointer which wake one step at a time waked k steps).the distance between the start node of cycle and the first meeting node is m, so...s=k-m,
s=nr-m=(n-1)r+(r-m),here we takes n = 1..so, using one pointer start from the start node of list, another pointer start from the first meeting node, all of them wake one step at a time, the first time they meeting each other is the start of the cycle.
*/
146 手动LRU,不会做
147. 148.linked list型 插入排序,归并排序,看discuss练好英文
149 判断最多有多少点在一条直线上,本来想记录斜率,但精度不够,顺便说一下double,float类型小数后面出现连续7个一样的数,就会自动四舍五入,用pair存储斜率就行
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
class Solution {
public:
int gcd(int a, int b)
{
if(b == )
return a;
return gcd(b, a % b);
}
int maxPoints(vector<Point>& points){
Point a,b;
int ans=,tot=;
double k=;
Point w;
map<pair<int,int>,int> mp;
int n=points.size();
if(n==) return ;
for(int i=;i<n;i++){
int Max=;
tot=;
for(int j=i+;j<n;j++){
if(i==j) continue;
a=points[i];
b=points[j];
if(a.x==b.x&&a.y==b.y){
tot++;
continue;
}
pair<int,int> w;
if(a.x==b.x){
w.first=;
w.second=;
k=,mp[w]++;
}
else{
int gc=gcd((a.x-b.x),a.y-b.y);
w.first=(a.x-b.x)/gc;
w.second=(a.y-b.y)/gc;
mp[w]++;
}
Max=max(Max,mp[w]);
}
ans=max(ans,Max+tot);
mp.clear();
}
return ans+; }
};
150.水
class Solution {
public:
int cal(string s){
int sum=;
int flag=;
int i=;
if(s[]=='-') i=,flag=-;
for(;i<s.length();i++){
sum=s[i]-''+sum*;
}
return sum*flag;
}
int evalRPN(vector<string>& tokens) {
stack<int> st;
int n=tokens.size();
int num1,num2,ans=;
for(int i=;i<n;i++){
string w=tokens[i];
if(w[]<=''&&w[]>=''||(w[]=='-'&&w[]<=''&&w[]>='')){
st.push(cal(w));
}
else{
num1=st.top();
st.pop();
num2=st.top();
st.pop();
if(w[]=='/'){
ans=num2/num1;
}
else if(w[]=='*'){
ans=num2*num1;
}
else if(w[]=='+'){
ans=num2+num1;
}
else if(w[]=='-'){
ans=num2-num1;
} st.push(ans);
}
}
return st.top();
}
};
151.水,代码比较丑陋
void reverseWords(string &s) {
int n=s.size()+;
if(n==) return;
s+=' ';
string ans;
int pos=;
for(int i=;i<n;i++){
while(s[i]==' '){
i++;
}
if(i==n) break;
pos=i;
while(s[i]!=' '){
i++;
}
if(ans.length()==){
ans=s.substr(pos,i-pos);
}
else
ans=s.substr(pos,i-pos)+' '+ans;
pos=i+;
}
s=ans;
return;
}
152.连续最大积,蠢哭了我
class Solution {
public:
int maxProduct(vector<int>& nums) {
int n=nums.size();
vector<int> Max(n+,);
vector<int> Min(n+,);
int ans=nums[];
Min[]=Max[]=nums[];
for(int i=;i<n;i++){
Max[i]=max(nums[i],max(Max[i-]*nums[i],Min[i-]*nums[i]));
Min[i]=min(nums[i],min(Min[i-]*nums[i],Max[i-]*nums[i]));
ans=max(ans,Max[i]);
}
return ans;
}
};
153,154很棒的两题。对于一个折过的有序序列进行二分查找
162 给一段数字,寻找peak元素,即比左右元素大的数,您的好友智商已下线。。。
164 radix sort,基数排序
188 刷新了leetcode的新难度,感觉目前最难,dp,交易来交易去很麻烦
200.一堆bash题和一堆水题
Leetcode 记录(101~200)的更多相关文章
- Java基础知识强化04:判断101~200之间有多少素数
1. 判断101~200之间有多少素数? package himi.hebao; /** * (1).编写函数isPrime()用来判断输入数据是否为素数 (2).遍历判断101~200之间的数据是否 ...
- java例题_02 101~200以内的素数
1 /*2 [程序 2 输出素数] 2 题目:判断 101-200 之间有多少个素数,并输出所有素数. 3 程序分析:判断素数的方法:用一个数分别去除 2 到 sqrt(这个数),如果能被整除,则表明 ...
- Leetcode之101. Symmetric Tree Easy
Leetcode 101. Symmetric Tree Easy Given a binary tree, check whether it is a mirror of itself (ie, s ...
- Leetcode 笔记 101 - Symmetric Tree
题目链接:Symmetric Tree | LeetCode OJ Given a binary tree, check whether it is a mirror of itself (ie, s ...
- LeetCode记录(1)——Array
1.Two Sum naive 4.Median of Two Sorted Arrays 找两个已排序数组的中位数 直接数可以过,但很蠢,O(m+n)时间 class Solution { publ ...
- 【一天一道LeetCode】#101. Symmetric Tree
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...
- Leetcode 记录(1~100)
5.回文串 几种方法: 暴力:枚举每一个字串,判断是否为回文串,复杂度O(n^3),暴力月莫不可取 dp:区间dp思想,O(n^2) 中心扩展:找每一个字符,然后往两边扩展,O(n^2) manach ...
- leetcode记录-罗马数字转整数
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M. 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 例如, 罗马数字 2 写做 II ,即为两个并 ...
- LeetCode记录之9——Palindrome Number
LeetCode真是个好东西,本来闲了一下午不想看书,感觉太荒废时间了就来刷一道题.能力有限,先把easy的题目给刷完. Determine whether an integer is a palin ...
随机推荐
- oracle 12c ORA-01017:invalid username/password; logon denied
Oracle 12C 中,想通过操作系统认证登录Oracle 数据库,有一些要注意的地方.不然就会遇到 ORA-01017:invalid username/password; logon denie ...
- Spring Boot学习--项目启动时执行指定service的指定方法
Springboot给我们提供了两种“开机启动”某些方法的方式:ApplicationRunner和CommandLineRunner. 这两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方 ...
- 发布WebApi项目时,提示未包含bin\yourDocumentationFile.xml文档文件
Open your publishprofile (*.pubxml) and include this code into "Project" element: <Item ...
- html5 之 local storage \sessjion storage
转载: HTMl5的sessionStorage和localStorage html5中的Web Storage包括了两种存储方式:sessionStorage和localStorage. sessi ...
- Python_面向对象_类1
面向对象:减少重复代码,提高效率,比函数式编程更高效 类的创建: 实例属性又称:成员变量,成员属性(或者字段) 面向对象的三大特性: 一.封装 把客观事物封装为抽象的类,并对外只暴露一个可用接口 使用 ...
- Elasticsearch集群架构的部署和调优(一)
[root@es-node1 ~]# mkdir /usr/java[root@es-node1 ~]# tar zxvf jdk1.8.0_131.tar.gz -C /usr/java/ [roo ...
- python3改版后的特征
1.原始数据类型和运算符 # 整数 3 # => 3 # 算术没有什么出乎意料的 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 # 但是除法 ...
- appium---第三个脚本,进入评论页,发表评论
#进入编辑页,点击编辑框,固定光标 #com.xxx.xxx:id/edit__content drive.find_element_by_id('/edit_content').click(); t ...
- BZOJ1096 [ZJOI2007]仓库建设 动态规划 斜率优化
原文链接http://www.cnblogs.com/zhouzhendong/p/8696410.html 题目传送门 - BZOJ1096 题意 给定两个序列$a,b,X$,现在划分$a$序列. ...
- git 错误解决
1.今天 当我 执行 git add somefile 的时候,出现 如下 错误: If no other git process is currently running, this prob ...