leetcode 题解代码整理 21-25题

Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two
lists.

合并两个有序链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution
{
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
    {
        ListNode *ans,*head;
        if (l1==NULL && l2==NULL ) return NULL;

        if (l1==NULL)
        {
            head=l2;
            l2=l2->next;
        }
        else
        if (l2==NULL)
        {
            head=l1;
            l1=l1->next;
        }
        else
        {
            if (l1->val < l2->val)
            {
                head=l1;
                l1=l1->next;
            }
            else
            {
                head=l2;
                l2=l2->next;
            }
        }
        ans=head;
        while (l1!=NULL || l2!=NULL)
        {
            if (l1==NULL)
            {
                ans->next=l2;
                ans=l2;
                l2=l2->next;
            }
            else
            if (l2==NULL)
            {
                ans->next=l1;
                ans=l1;
                l1=l1->next;
            }
            else
            {
                if (l1->val < l2->val)
                {
                    ans->next=l1;
                    ans=l1;
                    l1=l1->next;
                }
                else
                {
                    ans->next=l2;
                    ans=l2;
                    l2=l2->next;
                }
            }
        }
        return head;
    }
};

Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

输出所有的括号匹配

class Solution
{
vector<string>ans;
public:
    vector<string> generateParenthesis(int n)
    {

        string mark="";
        dfs(mark,n,n);
        return ans;
    }
private:
    void dfs(string mark,int x,int y)
    {
        if (x+y==0)
        {
            ans.push_back(mark);
            return ;
        }
        if (x!=0)
            dfs(mark+"(",x-1,y);
        if (x<y)
            dfs(mark+")",x,y-1);
    }
};

Merge k Sorted Lists

Merge k sorted
linked lists and return it as one sorted list. Analyze and describe its complexity.

对K个有序链表排序

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class ListNodeCompare
{
public:
    bool operator()(ListNode *l1,ListNode *l2)
    {
        return l1->val > l2->val;
    }
};
class Solution
{
public:
    ListNode* mergeKLists(vector<ListNode*>& lists)
    {
        ListNode *ans,*head,*p;
        priority_queue<ListNode*,vector<ListNode*>,ListNodeCompare>q;
        if (lists.size()==0) return NULL;
        ans=(ListNode*)malloc(sizeof(ListNode));
        ans->next=NULL;
        head=ans;
        for (int i=0;i<lists.size();i++)
        if (lists[i]!=NULL)
            q.push(lists[i]);

        while (!q.empty())
        {
            p=q.top();
            q.pop();
            ans->next=p;
            ans=ans->next;
            if (p->next!=NULL)
                q.push(p->next);
        }
        return head->next;
    }
};

Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

For example,

Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

对链表中每两个节点交换一下

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution
{
public:
    ListNode* swapPairs(ListNode* head)
    {
        ListNode *p1,*pre,*p2;
        if (head==NULL || head->next==NULL) return head;

        p1=head;
        pre=head;

        while (1)
        {
            p2=p1->next;
            p1->next=p2->next;
            p2->next=p1;
            if (pre==head)
                head=p2;
            else
                pre->next=p2;

            pre=p1;
            p1=p1->next;
            if (p1==NULL || p1->next==NULL) break;
        }
        return head;
    }
};

Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,

Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

对链表中每k个节点进行一次反转

class Solution
{
public:
    ListNode* reverseKGroup(ListNode* head, int k)
    {
        int n=k;
        int len=0;
        ListNode *p=head;
        if (head==NULL || head->next==NULL || k<=1)     return head;
        while (p)
        {
            len++;
            p=p->next;
        }
        if (n>len) return head;
        ListNode *q=head;
        while (n--)
        {
            ListNode *ne=q->next;
            q->next=p;
            p=q;
            q=ne;
        }

        if (len-k>=k)
            head->next= reverseKGroup(q,k);
        else
            head->next=q;
        return p;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-26 17:30:48

leetcode 题解代码整理 21-25题的相关文章

leetcode 题解代码整理 36-40题

Valid Sudoku Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. A partially filled sudoku which is valid. 判断数独当前状态是否合法 class Solut

leetcode 题解代码整理 1-5题

Two Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please no

leetcode 题解代码整理 31-35题

Next Permutation Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending orde

leetcode 题解代码整理 6-10题

ZigZag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line

【题解整理】二分题

[题解整理]二分题 题目类型: 二分查找: 二分答案. 大致解题思路: 查找注意有序和返回值: 浮点数注意精度: 整数注意返回值,建议另外维护一个变量,用于储存可行解. 题目 分类 传送门 WA点 poj 2785 二分查找 题解 lightoj 1088 二分查找 题解 lightoj 1307 二分查找 题解 longlong poj 2456 整数二分答案 题解 poj 3104 整数二分答案 题解 poj 3258 整数二分答案 题解 poj 3273 整数二分答案 题解 lightoj

【LeetCode】树(共94题)

[94]Binary Tree Inorder Traversal [95]Unique Binary Search Trees II (2018年11月14日,算法群) 给了一个 n,返回结点是 1 - n 的所有形态的BST. 题解:枚举每个根节点 r, 然后递归的生成左右子树的所有集合,然后做笛卡尔积. 1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *

[LeetCode]题解(python):031-Next Permutation

题目来源 https://leetcode.com/problems/next-permutation/ Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible

leetcode题解:Search in Rotated Sorted Array(旋转排序数组查找)

题目: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no du

leetcode题解:Binary Tree Postorder Traversal (二叉树的后序遍历)

题目: Given a binary tree, return the postorder traversal of its nodes' values. For example:Given binary tree {1,#,2,3}, 1 2 / 3 return [3,2,1]. Note: Recursive solution is trivial, could you do it iteratively? 说明: 1) 两种实现,递归与非递归 , 其中非递归有两种方法 2)复杂度分析:时