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是什么方法,如果有知道的同学欢迎提供思路。

上一篇:ckplayer 参数设置详解


下一篇:hdu 5105