LeetCode的easy题集合(C++实现)二

1.Intersection of Two Linked Lists


Write a program to find the node at which the intersection of two singly linked lists begins.For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3
分析:链表相交后,指向相同的节点,所以末节点指针必定相等,从头到尾遍历两个链表,用两个变量分别记录链表长度,得到长度差num,让长链表先走n步,当两个链表指针相等时,必为第一个相交点。
 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(headA==NULL||headB==NULL)
          return NULL;
        ListNode* midA=headA;
        ListNode* midB=headB;
        int count1=0,count2=0;
        while(headA->next!=NULL)
        {
             headA=headA->next;
             count1++;
        }
        while(headB->next!=NULL)
        {
             headB=headB->next;
             count2++;
        }
        if(headA!=headB)
         return NULL;
        else
        {
        if(count1>count2)
        {
            int num=count1-count2;
            while(num>0)
            {
              midA=midA->next;
              num--;
            }
        }
        else
        {
          int num=count2-count1;
            while(num>0)
            {
              midB=midB->next;
              num--;
            }  
        }
        while(midA!=midB)
        {
            midA=midA->next;
            midB=midB->next;
        }
        return midA;
        }
    }

2.Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

class MinStack {
public:
     MinStack()
     {
         min=INT_MAX;
     }
    void push(int x) {
        if(x<min) min=x;
        mystack.push_back(x);
    }
    void pop() {
        if(mystack.back()==min)
        {
            mystack.pop_back();
            min=INT_MAX; int n=mystack.size();
            for(int i=0;i<n;i++)
            {
                if(mystack[i]<min)
                {
                    min=mystack[i];
                }
            }
        }
        else
        {
            mystack.pop_back();
        }
    }
    int top() {
        return mystack.back();
    }
    int getMin() {
        return min;
    }
    private:
    vector<int> mystack;
    int min;
};

3.Valid Palindrome

 

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

bool isPalindrome(string s) {
         int len=s.length();
         if(len<=1)
          return true;
         int i=0;
         while(i<len) 
         {
            while ((s[i]<'0' || (s[i]>'9'&&s[i]<'A') || (s[i]>'Z'&&s[i]<'a')|| s[i]>'z')&&i<len)
{
i++;
}
while ((s[len-1]<'0' || (s[len-1]>'9'&&s[len-1]<'A') || (s[len-1]>'Z'&&s[len-1]<'a')|| s[len-1]>'z')&&i<len)
{
len--;
}
if (i>=len)
{
return true;
}
             if(s[i]!=s[len-1]&&abs(s[i]-s[len-1])!=32)
             {
                 return false;
             }
             i++;
             len--;
         }
         return true;
 }

4.Pascal's Triangle

 

Given numRows, generate the first numRows of Pascal's triangle.For example, given numRows = 5,

Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
vector<vector<int> > generate(int numRows) {
        vector<vector<int> > res;
if (numRows < 1)  return res;
vector<int> row1(1, 1);
res.push_back(row1);
if (numRows== 1)
{
return res;
    }
for (int i = 1; i <numRows; i++)
{
vector<int> row;
row.push_back(1);
for (int j = 1; j < i; j++)
{
row.push_back(res.at(i - 1).at(j - 1) + res.at(i - 1).at(j));
}
row.push_back(1);
res.push_back(row);
}
return res;
    }

5.Pascal's Triangle II

 

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

vector<int> getRow(int rowIndex) {
        vector<int> result;
        result.push_back(1);
        for(int i=1;i<=rowIndex;i++)
        {
            int temp=1;
            for(int j=1;j<i;j++)
            {
                int last=result[j];
                result[j]=temp+result[j];
                temp=last;
            }
            result.push_back(1);
        }
        return result;
    }

6.Path Sum

 

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

该题实际就是一个深度优先遍历问题。

bool depth(TreeNode *root, int sum,int res)
    {
        if(root==NULL)
        return false;
        if(root->left==NULL&&root->right==NULL) 
        return sum==res+root->val;
        return depth(root->left,sum,res+root->val)||depth(root->right,sum,res+root->val);
    }
    bool hasPathSum(TreeNode *root, int sum) {
       depth(root,sum,0);
    }

7.Minimum Depth of Binary Tree

 

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

采用层次遍历的方法 

int minDepth(TreeNode *root) {
        if(root==NULL) return 0;
        TreeNode *p=root;
        int cur=0;
        queue<pair<TreeNode*, int> > res;
        res.push(make_pair(p,1));
        while(!res.empty())
        {
            pair<TreeNode*, int> cur=res.front();
            res.pop();
            if(cur.first->left==NULL&&cur.first->right==NULL) return cur.second;
            if(cur.first->left)
            {
                res.push(make_pair(cur.first->left,cur.second+1));
            }
            if(cur.first->right)
            {
                res.push(make_pair(cur.first->right,cur.second+1));
            }
        }
    }

8.Maximum Depth of Binary Tree

 

int maxDepth(TreeNode *root) {
        if(root==NULL) return 0;
        TreeNode *p=root;
        int result=0;
        queue<pair<TreeNode*, int> > res;
        res.push(make_pair(p,1));
        while(!res.empty())
        {
            pair<TreeNode*, int> cur=res.front();
            res.pop();
            if(cur.first->left)
            {
                res.push(make_pair(cur.first->left,cur.second+1));
            }
            if(cur.first->right)
            {
                res.push(make_pair(cur.first->right,cur.second+1));
            }
            result=cur.second;
        }
        return result;
    }

9.Balanced Binary Tree

 

Given a binary tree, determine if it is height-balanced.For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

int getDepth(TreeNode* tree, int currentDepth){
        if(tree == NULL){
            return currentDepth;
        }
        return max(getDepth(tree->left, currentDepth+1), 
                getDepth(tree->right, currentDepth+1));
    }
    bool isBalanced(TreeNode *root) {
        if(root==NULL) return true;
        int ldepth = getDepth(root->left, 1);
        int rdepth = getDepth(root->right, 1);
        
        if(abs(ldepth-rdepth) > 1){
            return false;
        }else{
            return isBalanced(root->left) && isBalanced(root->right);
        }
    }

10.Binary Tree Level Order Traversal

 

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]
vector<vector<int> > levelOrder(TreeNode *root) {
        vector<vector<int> > ret;
        
        if(root==NULL) return ret;
        vector<int> a;
        TreeNode *p=root;
        int curlevel=-1;
        queue<pair<TreeNode*, int> > res;
        res.push(make_pair(p,0));
        while(!res.empty())
        {
            pair<TreeNode*, int> cur=res.front();
            res.pop();
            if(cur.first->left)
            {
                res.push(make_pair(cur.first->left,cur.second+1));
            }
            if(cur.first->right)
            {
                res.push(make_pair(cur.first->right,cur.second+1));
            }
            if(curlevel!=cur.second)
            {
                if(curlevel!=-1)
                  ret.push_back(a);
                a.clear();
                curlevel=cur.second;
                a.push_back(cur.first->val);
            }
            else
                a.push_back(cur.first->val);
        }
        ret.push_back(a);
        return ret;
    }

11.Binary Tree Level Order Traversal II

 

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

同上,只需最后将容器翻转reverse(ret.begin(),ret.end());

12.Symmetric Tree

 

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

bool ismirrir(TreeNode* left,TreeNode* right)
    {
        if(left==NULL&&right==NULL) return true;
        if((left==NULL&&right!=NULL)||(left!=NULL&&right==NULL)||left->val!=right->val) return false;
        return ismirrir(left->right,right->left)&&ismirrir(left->left,right->right);
    }
    bool isSymmetric(TreeNode *root) {
        if(root==NULL)
        return true;
        return ismirrir(root->left,root->right);
    }

13.Same Tree

 

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.

采用先序遍历

bool preorder(TreeNode *p,TreeNode *q)
    {
        if(p==NULL&&q==NULL) return true;
        else if((p==NULL&&q!=NULL)||(q==NULL&&p!=NULL)) return false;
        else
        {
            if(p->val!=q->val) return false;
            return preorder(p->left,q->left)&&preorder(p->right,q->right);
        }
    }
    bool isSameTree(TreeNode *p, TreeNode *q) {
        bool res=preorder(p,q);
        return res;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值