刷穿LeetCode——Task01

前言:本科毕业1年半了,2021年1月份报名了DataWhale组织的LeetCode编程实践,每天3道题,这篇博客记录Task01。

02. 两数相加

给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
addtwonumber1
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.

这道题需要对单链表的定义和创建比较熟悉,构造一个链表节点,对输入的两个节点取value之和,并定义一个carry flag来判断是否进位,赋给新节点的value,依次遍历即可。直接给代码如下:

// Definition for singly-linked list.
// struct ListNode {
    
    
//     int val;
//     ListNode *next;
//     ListNode() : val(0), next(nullptr) {}      //构造函数,struct属性初始化
//     ListNode(int x) : val(x), next(nullptr) {}
//     ListNode(int x, ListNode *next) : val(x), next(next) {}
// };
class Solution {
    
    
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    
    
        ListNode head(0), *p = &head;
        int carry_flag = 0;
        while (l1 || l2 || carry_flag) {
    
    
            int temp = 0;
            if (l1 != nullptr) 
                temp += l1->val;
            if (l2 != nullptr)
                temp += l2->val;
            temp += carry_flag;

            carry_flag = temp / 10;
            temp %= 10;

            ListNode *next = l1 ? l1 : l2;
            if (next == nullptr) next = new ListNode(temp);
            next->val = temp;

            p->next = next;
            p = p->next;
            l1 = l1 ? l1->next : nullptr;
            l2 = l2 ? l2->next : nullptr;
        }
        return head.next;
    }

稍微说明一下:LeetCode的在线解释器是把我们的代码放在服务器沙盒里跑,已经预编译好了各种常用的数据结构。在这个例子中服务器对于ListNode L1=[2,4,3]有一套解释代码,能够逆序存放各个value,以及main函数里运行Solution这些都有解释代码,我们只需创建符合题目规范的用例就能执行。*

04. 寻找两个正序数组的中位数

给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。
进阶:你能设计一个时间复杂度为 O(log (m+n)) 的算法解决此问题吗?
示例 2:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5

这道题是hard级别,简单总结一下:对于两个正序数组,都划分为两部分,使得左半部分最大值小于等于右半部分最小值,用二分查找法找到符合要求的划分点。这道题需要有一定数学分析并熟练使用binary search,我确实读了很久LeetCode网站上大佬写的solution,在此贴出来帮助后续回顾:
findMedianSortedArrays_1findMedianSortedArrays_2findMedianSortedArrays_3C++代码如下:

#include <iostream>
#include <vector>      
#include <stdlib.h>
#include <string>
#include <sstream>

using namespace std;


class Solution {
    
    
public:
    double findMedianSortedArrays(vector<int> & nums1, vector<int> & nums2) {
    
     
        int m = nums1.size();
        int n = nums2.size();
        if (m > n) {
    
        //to ensure m <= n
            vector<int> temp = nums1; nums1 = nums2; nums2 = temp;
            int tmp = m; m = n; n = tmp; 
            }
        
        // binary search for i
        int imin = 0, imax = m, halfLen = (m+n+1) / 2;
        while (imin <= imax) {
    
    
            int i = (imin + imax) / 2;
            int j = halfLen - i;
            if (i < imax && nums2[j-1] > nums1[i])   //i is too small
                imin = i + 1;
            else if (i > imin && nums1[i-1] > nums2[j]) //i is too large
                imax = i-1;
            else {
    
                                          // i is perfect
                    int maxLeft = 0;
                    //edge values
                    if (i == 0) maxLeft = nums2[j-1];
                    else if (j==0) maxLeft = nums1[i-1];
                    else maxLeft = max(nums1[i-1], nums2[j-1]);
                    
                    if ((m + n) % 2 == 1) 
                        return maxLeft;
                    else {
    
    
                        int minRight = 0;
                        if (i == m) minRight = nums2[j];
                        else if (j == n) minRight = nums1[i];
                        else minRight = min(nums1[i], nums2[j]);    
                        return (maxLeft + minRight) / 2.0;
                    }
                        
            }
        }
        return 0.0;
    }
};

int main(){
    
    
	Solution S;
    int array1[] = {
    
    1,3,5,6,9}, array2[] = {
    
    7,4,9,2};
    vector<int> nums1(begin(array1), end(array1));
    vector<int> nums2(begin(array2), end(array2));
    // int m = nums1.size();
    // for (int i = 0; i < m; i++) {
    
    
    //     cout << nums1[i] <<endl;
    // }
    cout << S.findMedianSortedArrays(nums1, nums2) << endl;
	system("pause");
	return 0;
}

//参考:[C++ STL] vector使用详解 (顺序容器,存放任意类型的动态数组))
// https://www.cnblogs.com/linuxAndMcu/p/10259630.html

05. 最长回文子串

给你一个字符串 s,找到 s 中最长的回文子串。
示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。

解题思路:对输入字符串每个位置,定义两个索引变量b和e进行正反向查找字符是否相同,记录当下的回文子字符长度,并将b, e赋值给额外定义的两个变量start和last;如此遍历整个字符串,打擂台算法找到最长的回文子字符长度,注意遍历时分奇偶。代码如下:


#include <iostream>
#include <string>
using namespace std;
#include <stdlib.h>
using std::string;

class Solution {
    
    
	public:
		string longestPalindrome(string s) {
    
    
			int len = s.size();
			if (len == 0) return s;
			int start = 0, last = 0;
			for (int i = 0; i < len - 1; ++i)  //分奇偶,以各个元素为中心左右遍历查找回文子字符串
			{
    
    
				longestPalindrome(s, i, i, start, last);
				longestPalindrome(s, i, i + 1, start, last);
			}
			
			return s.substr(start, last - start + 1);
		}
		void longestPalindrome(const string &s, int b, int e, int &start, int &last) {
    
    
		int len = s.size();
		while (b >= 0 && e < len && s[b] == s[e])
			--b, ++e;
		++b, --e; //返回一格
		if (e - b > last - start) {
    
    
			start = b;
			last = e;
		}
	}
};

int main(){
    
    
	Solution S;
	string substring;
	substring = S.longestPalindrome("abbabbua");
	cout<<substring<<endl;
	system("pause");
	return 0;
}

// 参考:https://github.com/pezy/LeetCode/tree/master/004.%20Longest%20Palindromic%20Substring

说明:许多代码都是看大佬写的,自己目前还很弱。本科所学的C++和算法与数据结构太浅了,许多C++特性和算法都未深入了解,代码也写得很少,希望自己能坚持每天刷题,勤于求教与记录总结,提升coding能力!

猜你喜欢

转载自blog.csdn.net/qq_33007293/article/details/112504587