Leetcode刷題筆記(CPP)


1. 兩數之和

在這裏插入圖片描述

利用map容器“一對一”記錄兩數關係. 主要思路是查找對偶數other是否被記錄, 如果無,則將當前元素作爲對偶數存入map;如果存在對偶數,則返回二者的索引. 時間複雜度O(n)O(n), 空間複雜度O(n)O(n)

class Solution 
{
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        map<int, int> record;
        for(int i=0; i<nums.size(); i++)
        {
            int other = target - nums[i];
            if(record.count(other))
            {
                return {i, record[other]};
            }
            else
            {
                other = nums[i];
                record[other] = i;
            }
        }
        return {-1,-1};
    }
};

2. 兩數相加

在這裏插入圖片描述
考慮創建啞節點dummy,使用dummy->next表示真正的頭節點,避免空邊界. 時間複雜度 O(n)O(n)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* first = new ListNode(0);  // 啞結點
        ListNode* last = first;
        int carry = 0;
        while(l1 or l2 or carry){
            // 相加
            int bitsum = 0;
            if(l1){
                bitsum += l1->val;
                l1 = l1->next;
            }
            if(l2){
                bitsum += l2->val;
                l2 = l2->next;
            }
            if(carry){
                bitsum += carry;
            }
            // 結果
            int digit = bitsum % 10;
            carry = bitsum / 10;
            // 鏈表存儲
            ListNode* node = new ListNode(digit);
            last->next = node;
            last = node;
        }
        last = first->next;
        delete first;
        return last;
    }
};

3. 無重複字符的最長子串

在這裏插入圖片描述

以滑動窗口的方式來尋找子串, 左指針在遇到重複元素時更新, 右指針即遍歷指針i. 時間複雜度 O(n)O(n)

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        length = l = r = 0
        while r<len(s):
            if s[r] not in s[l:r]:
                r += 1
                length = max(length, r-l)
            else:
                l += 1
        return length   

用python做算法實現,效率不高,但是很好理解。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章