写在前面:
因为要准备面试,开始了在[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 刷题记录的更多相关文章

  1. leetcode刷题记录--js

    leetcode刷题记录 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但 ...

  2. Leetcode刷题记录(python3)

    Leetcode刷题记录(python3) 顺序刷题 1~5 ---1.两数之和 ---2.两数相加 ---3. 无重复字符的最长子串 ---4.寻找两个有序数组的中位数 ---5.最长回文子串 6- ...

  3. LeetCode 刷题记录(二)

    写在前面:因为要准备面试,开始了在[LeetCode]上刷题的历程.LeetCode上一共有大约150道题目,本文记录我在<http://oj.leetcode.com>上AC的所有题目, ...

  4. LeetCode刷题记录(python3)

    由于之前对算法题接触不多,因此暂时只做easy和medium难度的题. 看完了<算法(第四版)>后重新开始刷LeetCode了,这次决定按topic来刷题,有一个大致的方向.有些题不止包含 ...

  5. leetcode 刷题记录(java)-持续更新

    最新更新时间 11:22:29 8. String to Integer (atoi) public static int myAtoi(String str) { // 1字符串非空判断 " ...

  6. leetcode刷题记录——树

    递归 104.二叉树的最大深度 /** * Definition for a binary tree node. * public class TreeNode { * int val; * Tree ...

  7. leetCode刷题记录

    (1)Linked List Cycle Total Accepted: 13297 Total Submissions: 38411 Given a linked list, determine i ...

  8. 算法进阶之Leetcode刷题记录

    目录 引言 题目 1.两数之和 题目 解题笔记 7.反转整数 题目 解题笔记 9.回文数 题目 解题笔记 13.罗马数字转整数 题目 解题笔记 14.最长公共前缀 题目 解题笔记 20.有效的括号 题 ...

  9. leetcode刷题记录——链表

    使用java实现链表 单向链表 双向链表 单向循环链表 双向循环链表 题目记录 160.相交链表 例如以下示例中 A 和 B 两个链表相交于 c1: A: a1 → a2 c1 → c2 → c3 B ...

随机推荐

  1. LA 3516 Exploring Pyramids (记忆化搜索)

    题意 给定一个DFS序列,问能有多少树与之对应. 思路 设输入序列为S,dp(i, j)为子序列Si, Si+1, --, Sj对应的树的个数,则边界条件为d(i, i) = 1,且Si != Sj时 ...

  2. django - from django.db.models import F - class F

    F() 的执行不经过 python解释器,不经过本机内存,是生成 SQL语句的执行. # Tintin filed a news story! reporter = Reporters.objects ...

  3. #1406 - Data too long for column (转)

    转自:(http://blog.sina.com.cn/s/blog_5115a74c01008e40.html) ERROR (): Data too long for column 解决方法 修改 ...

  4. == Rickard Oberg & TheServerSide

    看了Hani Suleiman和Rickard Oberg ,发现其实每个所谓的权威都应该有被质疑的绝对,可能往往权威会令人觉得理所应当

  5. 【英语】Bingo口语笔记(76) - 不知如何应答的场景对话

  6. 10g中HASH GROUP BY引起的临时表空间不足

    原本在9i上可以顺利完成的CTAS脚本,迁移到10g后运行总是报“ORA-1652: unable to extend temp segment by 128 in tablespace TS_HQY ...

  7. MongoDB中shell基本使用

    1.创建一个数据库,名为foobar use foobar 这个foobar数据库没有被真正的被创建.只是在mongo的缓存中 但是直接离开的话,这个数据库会被mongo删除. 2.现在我们给foob ...

  8. 用VS2010打开vs2008

    用VS2010打开vs2008,对应的9.0.0.0版本,而应该该使用版本10.0.0.0 解决方案:修改配置文件.将Microsoft.ReportViewer的版本为9.0.0.0改为10.0.0 ...

  9. 分享15款为jQuery Mobile定制的插件

    jQuery Mobile 1.0 已经发布了, 做为jQuery的移动设备类库, 并且依靠着jQuery这个及其受欢迎的类库,必将带给大家不一样的使用体验,基于jQuery Mobile的插件开发必 ...

  10. Javascript的匿名函数

    一.什么是匿名函数?在Javascript定义一个函数一般有如下三种方式:函数关键字(function)语句:function fnMethodName(x){alert(x);}函数字面量(Func ...