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 ...
随机推荐
- win7x64安装wince6
Windows Embedded CE 安装方法 Wince的安装相对比较复杂,即使是一个Wince的老手,也可能遇到这样那样的问题.想来真是悲摧,Windows XP, Windows 7,64位, ...
- App开放接口api安全性—Token签名sign的设计与实现
前言 在app开放接口api的设计中,避免不了的就是安全性问题,因为大多数接口涉及到用户的个人信息以及一些敏感的数据,所以对这些接口需要进行身份的认证,那么这就需要用户提供一些信息,比如用户名密码等, ...
- 转深入学习heritrix---体系结构(Overview of the crawler)
Heritrix采用了模块化的设计,它由一些核心类(core classes)和可插件模块(pluggable modules)构成.核心类可以配置,但不能被覆盖,插件模块可以被由第三方模块取代. ( ...
- mysql利用存储过程批量插入数据
最近需要测试一下mysql单表数据达到1000W条以上时增删改查的性能.由于没有现成的数据,因此自己构造,本文只是实例,以及简单的介绍. 首先当然是建表: [sql]view plaincopy CR ...
- 三 最简单的 AndEngine 程序框架
package com.example.AndEngineExample; import org.anddev.andengine.engine.Engine;import org.anddev.an ...
- Apache PHP 安装问题 (SUSE Linux)
1. SUSE Linux配置命令如下: './configure' '--with-apxs2=/usr/local/apache2/bin/apxs' '--with-mysql' 2. 接下来 ...
- textile
textile 编辑 Textile是一个人性化的Web文本生成器,以简洁的方式提供HTML标签功能. 目录 1内容 ▪ 短语修饰符 ▪ 块修饰符 ▪ 链接 ▪ 属性 ▪ 排列 ▪ 表格 ▪ 图像 ...
- Golang做的验证码(2)
前面一篇文章介绍了2个用Golang做的验证码 http://www.cnblogs.com/ghj1976/p/3392847.html 这里再补充几个: 1.在GAE上使用的Google的验证码 ...
- html中的div、td 、p 等容器内强制换行和不换行的实现
div.td .p 等容器内强制换行和不换行,在某些情况下还是比较实用的,下面本文整理了一些相关方面的知识,并有具体的实现方法,需要的朋友可以参考下1.强制不换行,同时以省略号结尾. 代码如下:< ...
- bzoj1391 最大权闭合子图(also最小割、网络流)
一道裸的最小割的题,写一下只是练练手. 表示被卡M,RE不开心.一道裸题至于吗? 再次复习一下最大权闭合子图: 1.每一个点若为正权,与源点连一条容量为绝对值权值的边.否则连向汇点一条容量为绝对值权值 ...