LeetCode 刷题记录
写在前面:
因为要准备面试,开始了在[LeetCode]上刷题的历程。
LeetCode上一共有大约150道题目,本文记录我在<http://oj.leetcode.com>上AC的所有题目,以Leetcode上AC率由高到低排序,基本上就是题目由易到难。我应该会每AC15题就过来发一篇文章,争取早日刷完。所以这个第一篇就是最简单的15道题了。
部分答案有参考网上别人的代码,和leetcode论坛里的讨论,很多答案肯定有不完美的地方,欢迎提问,指正和讨论。
No.1 Single Number
Given an array of integers, every element appears twice ***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 result=;
while(n-->)result ^= A[n];
return result;
}
};
No.2 Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
/**
* 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 maxDepth(TreeNode *root) {
if(root == NULL) return ;
int i = maxDepth(root -> left)+;
int j = maxDepth(root -> right)+;
return i>j?(i):(j);
}
};
No3.Same Tree
Total Accepted: 5936 Total Submissions: 13839
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) { if((p==NULL&&q!=NULL)||(p!=NULL&&q==NULL)) return false;
if(p==NULL&&q==NULL) return true;
if(p->val != q->val) return false; bool Left = isSameTree(p->left, q->left); bool Right = isSameTree(p->right, q->right); if(Left==true&&Right==true)
return true;
else
return false; }
};
No4. Reverse Integer Total
Accepted: 6309 Total Submissions: 15558
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
class Solution {
public:
int reverse(int x) {
if(x==) return ;
int tmp1 = , tmp2 = ;
bool neg = false;
if(x<) {x*=-; neg = true;}
while()
{
tmp1 = x%;
tmp2 = tmp2 * + tmp1;
x /= ;
if(x==) break;
}
return neg==true?-tmp2:tmp2;
}
};
No.5 Unique Binary Search Trees
Total Accepted: 4846 Total Submissions: 13728
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
class Solution {
public:
int numTrees(int n) {
if (n==) return ;
if (n==) return ;
if (n==) return ;
int result = ;
for(int i = ; i <= n; i++)
{
result += numTrees(i-) * numTrees(n-i);
}
return result;
}
};
No.6 Best Time to Buy and Sell Stock II
Total Accepted: 4858 Total Submissions: 13819
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
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 = ;
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];
result+=high-low;
}
if(prices[i]<prices[i-]&&prices[i]<prices[i+j+])
{
low = prices[i];
}
i += j;
j = ;
}
if(prices[n-]>prices[n-]&&prices[n-]>low) result += prices[n-] - low;
return result;
}
};
No.7 Linked List Cycle Total
Accepted: 5888 Total Submissions: 16797
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *a, *b;
a = head;
b = head;
while(a!=NULL&&b!=NULL&&b->next!=NULL)
{
a = a->next;
b = b->next->next;
if(a==b) return true;
}
return false;
}
};
No.8 Remove Duplicates from Sorted List
Total Accepted: 5563 Total Submissions: 16278
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL||head->next == NULL) return head;
ListNode *a = NULL, *b = NULL;
int tmp = head->val;
a = head;
while(a->next != NULL)
{
b = a;
a = a->next;
while(a->val == tmp)
{
if(a->next == NULL)
{
b->next = NULL;
return head;
}
else
a = a->next;
}
tmp = a->val; b->next = a;
}
return head;
}
};
No.9 Search Insert Position
Total Accepted: 5302 Total Submissions: 15548
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
class Solution {
public:
int searchInsert(int A[], int n, int target) {
int low = , high = n-, mid = (n-)/;
while()
{
mid = ( low + high )/;
if(A[mid]==target) break;
if(low>high) break;
if(A[mid]>target)
{
high = mid - ;
}
if(A[mid]<target)
{
low = mid + ;
}
}
return A[mid]<target?(mid+):mid;
}
};
No.10 Populating Next Right Pointers in Each Node
Total Accepted: 5077 Total Submissions: 14927
Given a binary tree:
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
/ \
/ \ / \
After calling your function, the tree should look like:
-> NULL
/ \
-> -> NULL
/ \ / \
->->-> -> NULL
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if(root == NULL || root->left == NULL || root->right == NULL) return;
TreeLinkNode *l = NULL, *r = NULL;
l = root->left;
r = root->right;
l->next = r;
if(root->next!=NULL)
r->next = root->next->left;
else r->next = NULL;
connect(root->left);
connect(root->right);
}
};
No. 11 Binary Tree Preorder Traversal
Total Accepted: 5285 Total Submissions: 15850
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*Recursive solution is easy, here I follow the Note, forbid the recursive solution and solve it iteratively.*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> v;
v.clear();
if(root == NULL) return v;
stack <TreeNode *>s;
TreeNode *a=root;
while()
{
v.push_back(a->val);
if(a->right != NULL) s.push(a->right);
if(a->left != NULL)
{
a = a -> left;
continue;
}
if(s.empty())
break;
else {
a = s.top();
s.pop();
}
}
return v;
}
};
No. 12 Binary Tree Inorder Traversal
Total Accepted: 5847 Total Submissions: 17520
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {,#,,},
\
/
return [,,].
Note: Recursive solution is trivial, could you do it 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:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> v;
v.clear();
if(root == NULL) return v;
stack <TreeNode *>s;
TreeNode *a=root, *b=NULL, *c=NULL;
while()
{ if(a->left != NULL)
{
b = a;
a = a -> left;
b -> left = NULL;
s.push(b);
continue;
}
v.push_back(a->val);
if(a->right != NULL)
{
a = a->right;
continue;
}
if(s.empty())
break;
else {
a = s.top();
s.pop();
}
}
return v;
}
};
No.13 Remove Element
Total Accepted: 5206 Total Submissions: 15760
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int m = n;
vector <int> B;
for(int i = ; i < n; i++)
{
if(A[i]==elem) continue;
else
B.push_back(A[i]);
}
for(int i = ; i< B.size(); i++)
{
A[i] = B[i];
}
return B.size();
}
};
No.14 Remove Duplicates from Sorted Array
Total Accepted: 5501 Total Submissions: 16660
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n<) return n;
vector<int> B;
B.push_back(A[]);
for(int i=; i< n; i++)
{
if(A[i]==A[i-])continue;
else
B.push_back(A[i]);
}
for(int i=; i<B.size(); i++)
{
A[i] = B[i];
}
return B.size();
}
};
No.15 Maximum Subarray
Total Accepted: 5278 Total Submissions: 16067
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
class Solution {
public:
int maxSubArray(int A[], int n) {
int tempstart = , sum= , max = -;
int i , start , end;
start = end = ;
for(i = ; i < n ; ++i)
{
if(sum < )
{
sum = A[i];
}
else
sum += A[i];
if(sum > max)
{
max = sum;
}
}
return max;
}
};
注: 不知道题目里说的divide and conquer approach是什么方法,如果有知道的同学欢迎提供思路。
LeetCode 刷题记录的更多相关文章
- leetcode刷题记录--js
leetcode刷题记录 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但 ...
- Leetcode刷题记录(python3)
Leetcode刷题记录(python3) 顺序刷题 1~5 ---1.两数之和 ---2.两数相加 ---3. 无重复字符的最长子串 ---4.寻找两个有序数组的中位数 ---5.最长回文子串 6- ...
- LeetCode 刷题记录(二)
写在前面:因为要准备面试,开始了在[LeetCode]上刷题的历程.LeetCode上一共有大约150道题目,本文记录我在<http://oj.leetcode.com>上AC的所有题目, ...
- LeetCode刷题记录(python3)
由于之前对算法题接触不多,因此暂时只做easy和medium难度的题. 看完了<算法(第四版)>后重新开始刷LeetCode了,这次决定按topic来刷题,有一个大致的方向.有些题不止包含 ...
- leetcode 刷题记录(java)-持续更新
最新更新时间 11:22:29 8. String to Integer (atoi) public static int myAtoi(String str) { // 1字符串非空判断 " ...
- leetcode刷题记录——树
递归 104.二叉树的最大深度 /** * Definition for a binary tree node. * public class TreeNode { * int val; * Tree ...
- leetCode刷题记录
(1)Linked List Cycle Total Accepted: 13297 Total Submissions: 38411 Given a linked list, determine i ...
- 算法进阶之Leetcode刷题记录
目录 引言 题目 1.两数之和 题目 解题笔记 7.反转整数 题目 解题笔记 9.回文数 题目 解题笔记 13.罗马数字转整数 题目 解题笔记 14.最长公共前缀 题目 解题笔记 20.有效的括号 题 ...
- leetcode刷题记录——链表
使用java实现链表 单向链表 双向链表 单向循环链表 双向循环链表 题目记录 160.相交链表 例如以下示例中 A 和 B 两个链表相交于 c1: A: a1 → a2 c1 → c2 → c3 B ...
随机推荐
- mysql分区(partition)
1)按范分区(range) partition by range(Year(birthday))( partition p0 values less than 1960, partition p1 v ...
- WEBUS2.0 In Action - [源代码] - C#代码搜索器
最近由于工作的需要, 要分析大量C#代码, 在数万个cs文件中搜索特定关键词. 这是一项非常耗时的工作, 用Notepad++要运行接近半个小时. 于是我利用WEBUS2.0 SDK创建了一个代码搜索 ...
- 监听器Listener
监听器 6个事件类,均以event结尾 *某些操作,如启动/关闭容器,创建/销毁会话,都将触发一种事件发生,当发生了某种事件,容器将创建对应的事件类对象 8个监听接口,均以Listener结尾 监听器 ...
- postgresql pg_hba.conf
pg_hba.conf是客户端认证配置文件 METHOD指定如何处理客户端的认证.常用的有ident,md5,password,trust,reject. PostgreSQL默认只监听本地端口,用n ...
- MongoDB配置客户端
新建mongodb27017.bat文件 内容为: mongo 127.0.0.1:27017/admin 连接成功! 来自为知笔记(Wiz)
- 句柄(handle)
< Back 句柄,在windows编程中用来标识: *.模块(module) *.任务(task) *.实例(instance) *.文件(file) *.内存块(block of memor ...
- (转)log4j:WARN No appenders could be found for logger 解决方案
我们在使用Log4j的时候,总是出现: log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.Log ...
- 性能测试-Jmeter
缘由 很多情况下我们写程序过程中只会对固定模块采取并发限制,而且asp.net对于多线程也有他自己的处理机制,尤其对于注重业务,结果导向的团队可能更注重一定时间节点给出满意的产品,但是你的模块到底是否 ...
- oracle10g库连接报错
- permission denied部署django 遇到没有python_egg_cache的问题解决
检查/etc/httpd/logs/error_log,看是否有如下错误: [Errno 13] Permission denied: '/var/www/.python-eggs' 这时候需要编辑“ ...