LeetCode 刷题记录(二)
写在前面:
因为要准备面试,开始了在[LeetCode]上刷题的历程。
LeetCode上一共有大约150道题目,本文记录我在<http://oj.leetcode.com>上AC的所有题目,以Leetcode上AC率由高到低排序,基本上就是题目由易到难。我应该会每AC15题就过来发一篇文章,争取早日刷完。所以这个第二篇还是相对比较简单的15道题了。
部分答案有参考网上别人的代码,和leetcode论坛里的讨论,很多答案肯定有不完美的地方,欢迎提问,指正和讨论。
No.16
Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
class Solution {
public:
int climbStairs(int n) {
if(n==) return ;
if(n==) return ;
if(n==) return ;
int A[n];
A[] = ;
A[] = ;
for(int i=; i<n; i++)
{
A[i] = A[i-] + A[i-];
}
return A[n-];
}
};
No.17
Roman to Integer
Total Accepted: 3141 Total Submissions: 9694
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
class Solution {
public:
int romanToInt(string s) {
int result = ;
for(int i = ; i<s.length(); i++)
{
switch (s[i])
{
case 'I':
{
if((i+) < s.length()){
switch (s[i+])
{
case 'V':
result += ;
i++;
break;
case 'X':
result += ;
i++;
break;
default: result += ;
}
}
else result += ;
}
break;
case 'X':
{
if((i+)<s.length()){
switch (s[i+])
{
case 'L':
result += ;
i++;
break;
case 'C':
result += ;
i++;
break;
default:
result += ;
}
}
else result += ;
}
break;
case 'C':
{
if((i+)<s.length()){
switch(s[i+])
{
case 'D':
result += ;
i++;
break;
case 'M':
result += ;
i++;
break;
default:
result += ;
}
}
else result += ;
}
break;
case 'V':
result += ;
break;
case 'L':
result += ;
break;
case 'M':
result += ;
break;
case 'D':
result += ;
break;
}
}
return result;
}
};
No.17
Symmetric Tree
Total Accepted: 5574 Total Submissions: 17286
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
/ \
/ \ / \
But the following is not:
/ \
\ \
Note:
Bonus points if you could solve it both recursively and iteratively.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int help(TreeNode *left, TreeNode *right)
{
if(left==NULL&&right==NULL) return true;
if(left==NULL||right==NULL) return false;
if(left->val!=right->val) return false;
return(help(left->left,right->right)&&help(left->right,right->left)); }
bool isSymmetric(TreeNode *root) {
if(!root) return true; return help(root->left,root->right);
}
};
No.18
Merge Two Sorted Lists
Total Accepted: 5328 Total Submissions: 16521
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(!l1||!l2)
return l1==NULL?l2:l1;
ListNode *p = l1, *q = l2, *tmp = NULL,*tmp2 = NULL, *head=NULL;
if(p->val<=q->val)
head = p;
else
head = q; while(p&&q)
{
if(p->val<=q->val)
{
if(p->next)
{
tmp = p;
p = p->next;
continue;
}
else
{
p->next = q;
return head;
}
}
else
{
if(tmp)
{
tmp -> next = q;
tmp2 = q;
q = p;
p = tmp2;
}
else
{
tmp2 = q;
q = p;
p = tmp2;
}
} }
return head; }
};
No.19
Convert Sorted Array to Binary Search Tree
Total Accepted: 4576 Total Submissions: 14314
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void insert_Node(TreeNode* &p, int q)
{
if(!p)
{
//TreeNode *tmp =NULL;
p = (TreeNode*)malloc(sizeof(struct TreeNode));
p->left = NULL;
p->right = NULL;
p->val = q;
return;
}
if(q>p->val)
insert_Node(p->right, q);
else
insert_Node(p->left, q);
}
void Insert(TreeNode* &p, vector<int> &num, int low, int high)
{
if(low>high) return;
int mid = (low+high)/;
insert_Node(p,num[mid]);
Insert(p, num, low, mid-);
Insert(p, num, mid+, high);
}
TreeNode *sortedArrayToBST(vector<int> &num) {
if(num.empty())
return NULL;
TreeNode *root=NULL; //= (TreeNode*)malloc(sizeof(TreeNode));
int low = , high = num.size();
// int mid = (low + high)/2; Insert(root, num, low, high-); return root;
}
};
No.20
Merge Sorted Array
Total Accepted: 5000 Total Submissions: 15668
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
if(!m&&n)
{
for(int i = ; i<n; i++)
A[i] = B[i];
}
if(!n) return;
int i = , j = , q = ;
while(i < m&&j < n && i+q<m+n)
{
if(A[i+q]<=B[j])
i++;
else
{
for(int k=m+q;k>i+q;k--)
{
A[k]=A[k-];
}
A[i+q++] = B[j++];
}
}
if(i==m)
{
for(int k = ; k+j<n; k++)
{
A[i+q+k] = B[j+k];
}
}
}
};
No.21
Swap Nodes in Pairs
Total Accepted: 4789 Total Submissions: 15074
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
if(!head) return NULL;
if(!(head->next)) return head;
ListNode *p = head, *q = head->next, *o = NULL, *tmp = NULL, *h = NULL;
o = (ListNode*)malloc(sizeof(struct ListNode));
//tmp = (ListNode*)malloc(sizeof(struct ListNode));
o->next = p;
int i = ;
bool flag = false;
if(!(q->next))
{
head = q;
q -> next = p;
p->next = NULL;
return head;
}
while(q->next)
{
if(!(i%))
{
if(p==head)
{
p->next = q->next;
q->next = p;
head = q;
//flag = true;
}
else
{
p->next = q->next;
o->next = q;
q->next = p;
}
tmp = p;
p = q;
q = tmp;
}
//if()
o = p;//o->next; p = q;//p->next;
q = q->next;
i++;
}
if(!(i%))
{
p->next = NULL;
o->next = q;
q->next = p;
} return head;
}
};
No.22
Pascal's Triangle
Total Accepted: 4251 Total Submissions: 13505
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[],
[,],
[,,],
[,,,],
[,,,,]
]
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<int> s,d;
vector<vector<int>> r;
s.push_back();
d.push_back();
d.push_back();
if(!numRows) return r;
r.push_back(s);
if(numRows==) return r;
r.push_back(d);
if(numRows==) return r;
int tmp = ;
for(int i = ; i<numRows; i++)
{
if(!(i%))
{
s.clear();
s.push_back();
for(int j = ; j<i-; j++)
{
tmp = d[j]+d[j+];
s.push_back(tmp);
}
s.push_back();
r.push_back(s);
}
if((i%))
{
d.clear();
d.push_back();
for(int j = ; j<i-; j++)
{
tmp = s[j]+s[j+];
d.push_back(tmp);
}
d.push_back();
r.push_back(d);
}
}
return r;
}
};
No.23
Best Time to Buy and Sell Stock
Total Accepted: 5232 Total Submissions: 16683
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size()<) return ;
if(prices.size() == ) return (prices[]-prices[])>?(prices[]-prices[]):;
int low = prices[], high = , result = , n = prices.size(), j = , tmp = ;
bool flag = false;
for( int i = ; i<n-; i++ )
{
while(prices[i+j]==prices[i+j+]) j++;
if(prices[i]>prices[i-]&&prices[i]>prices[i+j+])
{
high = prices[i];
tmp = high-low;
if(result<tmp)
result = tmp;
}
if(prices[i]<prices[i-]&&prices[i]<prices[i+j+])
{
if(low>prices[i])
low = prices[i];
}
i += j;
j = ;
}
if(prices[n-]>prices[n-]&&prices[n-]>low)
{
tmp = prices[n-] - low;
if(result<tmp)
result = tmp;
}
return result;
}
};
No.24
Balanced Binary Tree
Total Accepted: 5256 Total Submissions: 16787
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
static int tree_height(const TreeNode* root, bool& balanced) { const int left_height = root->left ? tree_height(root->left, balanced) + : ; if (!balanced) return ; const int right_height = root->right ? tree_height(root->right, balanced) + : ; if (!balanced) return ; const int diff = left_height - right_height; if (diff < - || diff > ) balanced = false; return (left_height > right_height ? left_height : right_height); }
bool isBalanced(TreeNode *root) {
bool balanced = true; if (root) tree_height(root, balanced); return balanced;
}
};
No.25
Integer to Roman
Total Accepted: 2969 Total Submissions: 9554
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
class Solution {
public:
string intToRoman(int num) {
string s;
s.clear();
while(num)
{
if(num>=)
{
s += "M";
num -= ;
continue;
}
else if(num>=)
{
s += "CM";
num -= ;
continue;
}
else if(num>=)
{
s += "D";
num -= ;
continue;
}
else if(num>=)
{
s += "CD";
num -= ;
continue;
}
else if(num>=)
{
s += "C";
num -= ;
continue;
}
else if(num>=)
{
s += "XC";
num -= ;
continue;
}
else if(num>=)
{
s += "L";
num -= ;
continue;
}
else if(num>=)
{
s += "XL";
num -= ;
continue;
}
else if(num>=)
{
s += "X";
num -= ;
continue;
}
else if(num>=)
{
s +="IX";
num -= ;
continue;
}
else if(num>=)
{
s +="V";
num -= ;
continue;
}
else if(num>=)
{
s +="IV";
num -= ;
continue;
}
else if(num>=)
{
s +="I";
num -= ;
continue;
}
}
return s;
}
};
No.26
Single Number II
Total Accepted: 5597 Total Submissions: 18201
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
class Solution {
public:
int singleNumber(int A[], int n) {
int count[] = {};
int result = ;
for(int i = ; i < n; i++)
{
for(int j = ; j<; j++)
{
if((A[i]>>j)&)
count[j]++;
if(!(count[j]%))
count[j] = ;
}
}
for(int i = ; i<; i++)
{
result += (count[i]<<i);
}
return result;
}
};
No.27
Binary Tree Level Order Traversal II
Total Accepted: 3757 Total Submissions: 12234
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7]
[9,20],
[3],
]
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<vector<int>> r;
vector<int> t;
public: int getDepth(TreeNode *root)
{
if(!root) return ;
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
return leftDepth>rightDepth?(leftDepth+):(rightDepth+);
}
void helper(TreeNode *root, int level)
{
if(!root||level<) return;
if(!level) t.push_back(root->val);
helper(root->left, level-);
helper(root->right, level-);
}
vector<vector<int> > levelOrderBottom(TreeNode *root) {
r.clear();
t.clear();
if(!root) return r;
int depth = getDepth(root);
for(int i = depth - ; i>-; i--)
{
helper(root,i);
r.push_back(t);
t.clear();
}
return r;
}
};
未完待续...
LeetCode 刷题记录(二)的更多相关文章
- leetcode刷题记录--js
leetcode刷题记录 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但 ...
- Leetcode刷题记录(python3)
Leetcode刷题记录(python3) 顺序刷题 1~5 ---1.两数之和 ---2.两数相加 ---3. 无重复字符的最长子串 ---4.寻找两个有序数组的中位数 ---5.最长回文子串 6- ...
- LeetCode刷题记录(python3)
由于之前对算法题接触不多,因此暂时只做easy和medium难度的题. 看完了<算法(第四版)>后重新开始刷LeetCode了,这次决定按topic来刷题,有一个大致的方向.有些题不止包含 ...
- leetcode 刷题记录(java)-持续更新
最新更新时间 11:22:29 8. String to Integer (atoi) public static int myAtoi(String str) { // 1字符串非空判断 " ...
- LeetCode 刷题记录
写在前面:因为要准备面试,开始了在[LeetCode]上刷题的历程.LeetCode上一共有大约150道题目,本文记录我在<http://oj.leetcode.com>上AC的所有题目, ...
- leetcode刷题记录——树
递归 104.二叉树的最大深度 /** * Definition for a binary tree node. * public class TreeNode { * int val; * Tree ...
- 算法进阶之Leetcode刷题记录
目录 引言 题目 1.两数之和 题目 解题笔记 7.反转整数 题目 解题笔记 9.回文数 题目 解题笔记 13.罗马数字转整数 题目 解题笔记 14.最长公共前缀 题目 解题笔记 20.有效的括号 题 ...
- leetCode刷题记录
(1)Linked List Cycle Total Accepted: 13297 Total Submissions: 38411 Given a linked list, determine i ...
- leetcode刷题记录——数组与矩阵
@ 目录 283. 移动零 566. 重塑矩阵 485. 最大连续1的个数 240. 搜索二维矩阵 II 378. 有序矩阵中第K小的元素 645. 错误的集合 287. 寻找重复数 667. 优美的 ...
随机推荐
- POJ2186 POPULAR COW
链接:http://poj.org/problem?id=2186 题意:给你N个点,然后在给你N条有向边,然后让你找出这样的点S,S满足条件图上任意一点都能到达S. 要想满足任意一点都能到达,首先满 ...
- kafka_2.9.2-0.8.1.1分布式集群搭建代码开发实例
准备3台虚拟机, 系统是RHEL64服务版. 1) 每台机器配置如下:$ cat /etc/hosts # zookeeper hostnames: 192.168.8.182 ...
- 总结swift 1.2适配swift2.0遇到的改变
swift1.2适配swift2.0 以下列举的是我在项目中遇到的需要修改的,基本常见的问题就没有罗列了. 1.find函数变成了为indexOf 2.sort变成了sortInPlace 3.sor ...
- PHP实现站点pv,uv统计(一)
具体步骤分为数据采集脚本,数据收取服务,数据分析脚本,数据存储服务 采集脚本一般有两种形式,一种是简单的页面插入一个图片进行请求,一种是复杂的动态生成js标签,引入一段js(这时采集服务器会网往客户端 ...
- SQL Server 2008 序列号
SQL Server 2008 序列号:Developer: PTTFM-X467G-P7RH2-3Q6CG-4DMYBEnterprise: JD8Y6-HQG69-P9H84-XDTPG-34 ...
- final修饰符,finally,finalize区别
1.final 如果一个类被声明为final,意味着它不能再派生出新的子类,不能作为父类被继承.因此,一个类不能即被声明为abstract,又被声明为final.将变量或方法声明为final,可以保证 ...
- mysql 在大型应用中的架构演变
文正整理自:http://www.csdn.net/article/2014-06-10/2820160 可扩展性 架构的可扩展性往往和并发是息息相关,没有并发的增长,也就没有必要做高可扩展性的架构, ...
- Android 动画 6问6答
1.view 动画有哪些需要注意的? 答:view动画 本身比较简单.http://www.cnblogs.com/punkisnotdead/p/5179115.html 看这篇文章的第五问就可以了 ...
- nodejs简单层级结构配置文件
在NodeJS中使用配置文件,有几种比较不错的方案:第一种:文件格式使用json是毋容置疑的好方案.格式标准,易于理解,文件内容读取到内存之后,使用JSON的标准分析函数即可得到配置项.第二种:将配置 ...
- mipmap 目录和drawable 目录有什么区别
Q :最近使用studio 发现drawle-hdpi 都没有了换成了mipmap-hdpi,这两个目录有什么区别呢,哪个比较好呢??? A: 我简单总结一下: 使用上没有任何区别,你把它当drawa ...