Bootstrap

【打卡】LeetCode 热题 HOT 100

LeetCode 热题 HOT 100

1. 两数之和

1.两数之和

class Solution {
public:
    unordered_map<int, int> m;
    vector<int> twoSum(vector<int>& nums, int target) {
        for (int i = 0; i < nums.size(); i++) {
            m[nums[i]] = i;
        }
        for (int i = 0; i < nums.size(); i++) {
            int b = target - nums[i];
            if (m[b] && m[b] != i) return {i, m[b]};
        }
        return {};
    }
};

2. 两数相加

2. 两数相加

/**
 * 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* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* h = new ListNode(0);
        ListNode* s = h;
        int t = 0;
        while(l1 || l2) {
            if (l1) {
                t += l1->val;
                l1 = l1->next;
            }
            if (l2) {
                t += l2->val;
                l2 = l2->next;
            }
            s->next = new ListNode(t % 10);
            s = s->next;
            t /= 10;
        }
        if (t) s->next = new ListNode(t);
        return h->next;
    }
};

3. 无重复字符的最长子串

3. 无重复字符的最长子串

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int ans = 0;
        set<char> st;
        int j = 0;
        for (int i = 0; i < s.size(); i++) {
            if (i) st.erase(s[i-1]);
            while (j < s.size() && st.count(s[j]) == 0) {
                st.insert(s[j]);
                j++;
            }
            ans = max(ans, j - i);
        }
        return ans;
    }
};

未完待续。。。

;