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 ...
随机推荐
- operator重载的使用
C++的大多数运算符都可以通过operator来实现重载. 简单的operator+ #include <iostream> using namespace std; class A { ...
- type tips
网上有这么一篇文章,全文如下:http://bbs.9ria.com/blog-220191-18429.html AS3中一共有以下六种获取变量类型的方法: typeof instanceof ...
- Maven与Ant的区别
相同点: Ant和Maven都是基于Java的构建(build)工具. 理论上来说,有些类似于(Unix)C中的make ,但没有make的缺陷.Ant是软件构建工具,Maven的定位是软件项目管理和 ...
- 如何正确选择MySQL数据列类型
MySQL数据列类型选择是在我们设计表的时候经常会遇到的问题,下面就教您如何正确选择MySQL数据列类型,供您参考学习. 选择正确的数据列类型能大大提高数据库的性能和使数据库具有高扩展性.在选择MyS ...
- Delphi 保存写字板程序, 并进行打印
wDoc := docapp1.Documents.open(ExtractFilePath(Paramstr(0)) + 'abc.doc'); wDoc.SaveAs(ExtractFilePat ...
- OSX 10.10安装教程。
现在苹果已经放出了OS X 10.9 Mavericks第一个开发者预览版,从Mac App Store中获得的安装程序,可以在10.8的系统中直接进行升级,原有文件都会保留.但是要想制作成一个10. ...
- php 在线 mysql 大数据导入程序
1 <?php header("content-type:text/html;charset=utf-8"); error_reporting(E_ALL); set_tim ...
- 【LeetCode】139 - Word Break
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...
- [质疑]编程之美求N!的二进制最低位1的位置的问题
引子:编程之美给出了求N!的二进制最低位1的位置的二种思路,但是呢?但是呢?不信你仔细听我道来. 1.编程之美一书给出的解决思路 问题的目标是N!的二进制表示中最低位1的位置.给定一个整数N,求N!二 ...
- 把一个序列转换成严格递增序列的最小花费 CF E - Sonya and Problem Wihtout a Legend
//把一个序列转换成严格递增序列的最小花费 CF E - Sonya and Problem Wihtout a Legend //dp[i][j]:把第i个数转成第j小的数,最小花费 //此题与po ...