编程Task1

1 数组

  • 支持动态扩容的数组

  c++中vector是支持动态扩容的数组,可以进行增删改操作

 

  • 实现两个有序数组合并为一个有序数组

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    /*
    for(int i=m;i<n+m;++i)
    {
        nums1[i]=nums2[i-m];
    }
        
        sort(nums1.begin(),nums1.end());
    */
        int i = m - 1, j = n - 1, writeIdx = m + n - 1;
        while (i >= 0 && j >= 0)
            nums1[writeIdx--] = nums1[i] > nums2[j]? nums1[i--] : nums2[j--];
        while (j >= 0)
            nums1[writeIdx--] = nums2[j--];
    }
};

2 链表

  • 链表反转

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
 
         ListNode *prev = NULL;
        while (head != NULL) {
            ListNode *temp = head->next;
            head->next = prev;
            prev = head;
            head = temp;
        }
        return prev;
        
    }
};

  •  两个有序链表合并

/**
 * 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) {
    
        if(l1 == NULL && l2 == NULL){
            return NULL;
        }
        
        if(l1 == NULL){
            return l2;
        }
        
        if(l2 == NULL){
            return l1;
        }
        
        if(l1->val < l2->val){
            l1->next = mergeTwoLists(l1->next,l2);
            return l1;
        }else{
            l2->next = mergeTwoLists(l1,l2->next);
            return l2;
        }
        
       
    }
};

求链表的中间结点

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
    int count = 0;
    ListNode *p1 = head, *p2 = head;
    while(p1)
    {
        p1 = p1->next;
        count++;
    }
    count = count / 2;
    while(count)
    {
        p2 = p2->next;
        count--;
    }
    return p2; 

    }
};

3.LEETCODE练习题

求众数:https://leetcode-cn.com/problems/majority-element/

求缺失的第一个正数:https://leetcode-cn.com/problems/first-missing-positive/

环形链表I:https://leetcode-cn.com/problems/linked-list-cycle/

合并k个排序链表:https://leetcode-cn.com/problems/merge-k-sorted-lists/

最优作业可参考:http://www.xuzhenggen.com/2019/02/28/python%E4%B8%AD%E6%95%B0%E7%BB%84%E4%B8%8E%E9%93%BE%E8%A1%A8%E7%9A%84%E8%AF%B4%E6%98%8E%E4%B8%8E%E5%AE%9E%E7%8E%B0/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值