Conquer Leetcode in c++ (1)

发布时间:2019-06-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Conquer Leetcode in c++ (1)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

写在前面:
因为要准备面试,开始了在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?
```c++
class Solution {
public:
int singleNumber(int A[], int n) {
int result=0;
while(n-->0)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. ```c++ /** * 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 0; int i = maxDepth(root -> left)+1; int j = maxDepth(root -> right)+1; 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.

```c++
/**
* 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 ```c++ class Solution { public: int reverse(int x) { if(x==0) return 0; int tmp1 = 0, tmp2 = 0; bool neg = false; if(x<0) {x*=-1; neg = true;} while(1) { tmp1 = x%10; tmp2 = tmp2 * 10 + tmp1; x /= 10; if(x==0) 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.
```c++
1 3 3 2 1
/ / /
3 2 1 1 3 2
/ /
2 1 2 3

```c++
class Solution {
public:
    int numTrees(int n) {
        if (n==0) return 1;
        if (n==1) return 1;
        if (n==2) return 2;
        int result = 0;
        for(int i = 1; i <= n; i++)
        {
            result += numTrees(i-1) * 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).

```c++
class Solution {
public:
int maxprofit(vector &prices) {
if(prices.size()<2) return 0;
if(prices.size() == 2) return (prices[1]-prices[0])>0?(prices[1]-prices[0]):0;
int low = prices[0], high = 0, result = 0, n = prices.size(), j = 0;
bool flag = false;
for( int i = 1; i<n-1; i++ )
{
while(prices[i+j]==prices[i+j+1]) j++;
if(prices[i]>prices[i-1]&&prices[i]>prices[i+j+1])
{
high = prices[i];
result+=high-low;
}
if(prices[i]<prices[i-1]&&prices[i]<prices[i+j+1])
{
low = prices[i];
}
i += j;
j = 0;

    }
    if(prices[n-1]>prices[n-2]&&prices[n-1]>low) result += prices[n-1] - 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? ```c++ /** * 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.

```c++
/**
* 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], 52 [1,3,5,6], 21 [1,3,5,6], 74 [1,3,5,6], 00 ```c++ class Solution { public: int searchInsert(int A[], int n, int target) { int low = 0, high = n-1, mid = (n-1)/2; while(1) { mid = ( low + high )/2; if(A[mid]==target) break; if(low>high) break; if(A[mid]>target) { high = mid - 1; } if(A[mid]<target) { low = mid + 1; } } return A[mid]<target?(mid+1):mid; } };

No.10 Populating Next Right Pointers in Each Node
Total Accepted: 5077 Total Submissions: 14927

Given a binary tree
```c++
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,
```c++
        1
       /  
      2    3
     /   / 
    4  5  6  7

After calling your function, the tree should look like:
```c++
1 -> NULL
/
2 -> 3 -> NULL
/ /
4->5->6->7 -> NULL




```c++ /** * 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?

```c++
/**
* 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 preorderTraversal(TreeNode *root) {
vector v;
v.clear();
if(root == NULL) return v;
stack s;
TreeNode *a=root;
while(1)
{
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 {1,#,2,3},
1

2
/
3
return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?
```c++
/**
 * 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(1)
        {

            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.
```c++
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int m = n;
vector B;
for(int i = 0; i < n; i++)
{
if(A[i]==elem) continue;
else
B.push_back(A[i]);
}
for(int i = 0; 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]. ```c++ class Solution { public: int removeDuplicates(int A[], int n) { if(n<2) return n; vector<int> B; B.push_back(A[0]); for(int i=1; i< n; i++) { if(A[i]==A[i-1])continue; else B.push_back(A[i]); } for(int i=0; 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.

```c++
class Solution {
public:
int maxSubArray(int A[], int n) {
int tempstart = 0 , sum=0 , max = -1000;
int i , start , end;
start = end = 0;
for(i = 0 ; i < n ; ++i)
{
if(sum < 0)
{
sum = A[i];
}
else
sum += A[i];
if(sum > max)
{
max = sum;
}
}
return max;

}

};
```
注: 不知道题目里说的divide and conquer approach是什么方法,如果有知道的同学欢迎提供思路。

脚本宝典总结

以上是脚本宝典为你收集整理的Conquer Leetcode in c++ (1)全部内容,希望文章能够帮你解决Conquer Leetcode in c++ (1)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。