Datawhale-LeetCode编程实践组队学习Task05

23. 合并K个升序链表


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* merge(ListNode* head1, ListNode* head2)
    {
        ListNode* ret = new ListNode(-1);
        ListNode* q = ret;
        while (head1 != nullptr && head2 != nullptr)
        {
            if (head1->val < head2->val)
            {
                q->next = new ListNode(head1->val);
                head1 = head1->next;
            }
            else
            {
                q->next = new ListNode(head2->val);
                head2 = head2->next;
            }
            q = q->next;
        }
        while (head1 != nullptr)
        {
            q->next = new ListNode(head1->val);
            head1 = head1->next;
            q = q->next;
        }
        while (head2 != nullptr)
        {
            q->next = new ListNode(head2->val);
            head2 = head2->next;
            q = q->next;
        }

        return ret->next;
    }
    ListNode* mergeLists(vector<ListNode*>& lists, int begin, int end)
    {
        if (begin >= end)
            return nullptr;
        if (begin + 1== end)
            return merge(lists[begin], nullptr);
        if (begin + 2 == end)
            return merge(lists[begin], lists[end - 1]);
        int middle = (begin + end) / 2;
        ListNode* front = mergeLists(lists, begin, middle);
        ListNode* back = mergeLists(lists, middle, end);
        return merge(front, back);
    }
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        int n = lists.size();
        return mergeLists(lists, 0, n);
    }
};

26. 删除排序数组中的重复项

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int first = 1;
        int second = 1;
        int n = nums.size();
        while (second < n)
        {
            if (nums[second] == nums[first - 1])
            {
                second++;
            }
            else
            {
                nums[first] = nums[second];
                first++;
                second++;
            }
        }

        return n > 0 ? first : 0;
    }
};

33. 搜索旋转排序数组

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n = nums.size();
        int i = 0;
        while (i < n && nums[i] < target && nums[i] >= nums[0]) i++;
        if (i < n && nums[i] == target) return i;
        i = n - 1;
        while (i >= 0 && nums[i] > target && nums[i] <= nums[n - 1]) i--;
        if (i >= 0 && nums[i] == target) return i;
        else return -1;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_43627017/article/details/112727344