Loading

【刷穿LeetCode】极简题解:1-10

LeetCode题解:1-10

image

1. 两数之和

解题思路

遍历数组的同时将{数字,下标}存入哈希表,同时判断当前遍历的数字是否在哈希表中有满足条件的解,若有则返回。

代码

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

2. 两数相加

解题思路

  • 枚举以i为尾端点的字串。尾端点往后移动时,它所对应的最靠左的端点j一定不动或向后移动。 $O(n)$
  • 用哈希表维护ji中字符出现的次数。

代码

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_map<char, int> cnt;
        int res = 0;
        for (int i = 0, j = 0; i < s.size(); i++) {
            cnt[s[i]]++;
            while (cnt[s[i]] > 1) {
                cnt[s[j]]--;
                j++;
            }
            res = max(res, i - j + 1);
        }
        return res;
    }
};

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

解题思路

  • 枚举以i为尾端点的字串。尾端点往后移动时,它所对应的最靠左的端点j一定不动或向后移动。 $O(n)$
  • 用哈希表维护ji中字符出现的次数。

代码

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_map<char, int> cnt;
        int res = 0;
        for (int i = 0, j = 0; i < s.size(); i++) {
            cnt[s[i]]++;
            while (cnt[s[i]] > 1) {
                cnt[s[j]]--;
                j++;
            }
            res = max(res, i - j + 1);
        }
        return res;
    }
};

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

解题思路

将两个数组合并、排序,判断数组长度奇偶并输出中位数。

代码

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        vector<int> num;
        num.insert(num.end(), nums1.begin(), nums1.end());
        num.insert(num.end(), nums2.begin(), nums2.end());

        int n = num.size();
        sort(num.begin(), num.end());
        
        double res = 0;
        if (n % 2 == 0) {
            res = ((double)num[n / 2 - 1] + num[n / 2]) / 2;
        } else {
            res = num[n / 2];
        }

        return res;
    }
};
posted @ 2022-05-02 20:01  AaronDi  阅读(29)  评论(0)    收藏  举报