LeetCode question brushing record

Posted by ionik on Wed, 12 Jan 2022 04:43:07 +0100

LeetCode question brushing record

4. Find the median of two positively ordered arrays

Solution idea: the topic requires to find the median of two ordered arrays. A very direct and clear idea is to combine the two ordered arrays into one ordered array, and then find the median mednum = (Num [len / 2] + num [(len - 1) / 2]) / 2. The time complexity is O(m+n), the space complexity is O(m+n), and the time complexity that cannot meet the requirements of the topic is O(log(m+n)).

class Solution
{
public:
    double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2)
    {
        return mergeArrays(nums1, nums2);
    }

    // O(m + n)
    double mergeArrays(vector<int> &nums1, vector<int> &nums2)
    {
        int len1 = nums1.size();
        int len2 = nums2.size();
        vector<int> nums3;
        int i = 0, j = 0;
        while (i < len1 && j < len2)
        {
            if (nums1[i] < nums2[j])
            {
                nums3.push_back(nums1[i++]);
            }
            else
            {
                nums3.push_back(nums2[j++]);
            }
        }

        while (i < len1)
        {
            nums3.push_back(nums1[i++]);
        }

        while (j < len2)
        {
            nums3.push_back(nums2[j++]);
        }

        // med = (num[i / 2] + num[(i - 1) / 2]) / 2
        int len3 = nums3.size();
        return len3 > 0 ? (nums3[len3 / 2] + nums3[(len3 - 1) / 2]) / 2.0 : 0;
    }
};

33. Search rotation sort array

Problem solving idea: the problem requires to find the target value in the array. The given array is orderly and rotated. The array can be traversed directly, but the time complexity can not meet the problem requirement O(logn). The idea is to use binary search. The key point is to judge whether the subarray is orderly after binary search.

class Solution {
    // Binary search
    public int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2; // Find the middle position of the array
            if (nums[mid] == target) {
                return mid;
            }

            if (nums[mid] >= nums[left]) { // The left half is ordered
                if (target < nums[mid] && target >= nums[left]) { 
                    right = mid - 1; // The target value is in the left half
                } else {
                    left = mid + 1;
                }
            } else {
                if (target > nums[mid] && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return -1;
    }
}

34. Find the first and last position of an element in a sorted array

Problem solving idea: the problem requires finding the start and end positions of the target value in an ordered array. You can directly traverse the entire array. The time complexity is O(n), but the topic requires the time complexity to be O(log2n). Because it is ordered, it can be obtained by binary search.

class Solution {
public:
    // Binary search
    vector<int> searchRange(vector<int>& nums, int target) {
        int left = 0, right = nums.size() - 1;  // Left boundary, right boundary

        // Find left boundary
        while (left <= right) {
            int mid = left + (right - left) / 2;  // Find the middle position of the array

            if (nums[mid] >= target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        // Boundary treatment
        int finLeft = (left < nums.size() && nums[left] == target) ? left : -1;

        // Seeking the right boundary -- the operation is the same as seeking the left boundary
        left = 0, right = nums.size() - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (nums[mid] <= target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        int finRight = (right > -1 && nums[right] == target) ? right : -1;

        return {finLeft, finRight};
    }
};

49. Grouping of acronyms

Problem solving idea: the problem requires grouping the letter ectopic words, so after sorting the ectopic words, they will become the same words. Therefore, you can use the hash table to group, sort the words first, and store the original words as keys and values.

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> strV;  // Store all group puzzles

        unordered_map<string, vector<string>> mp;
        // After reordering the words, determine whether the same words are grouped -- stored through a hash table
        for (auto&& str : strs) {
            string key = str;
            sort(key.begin(), key.end());
            mp[key].push_back(str);
        }

        // Store the grouped words in a container
        for (auto it = mp.begin(); it != mp.end(); it++) {
            strV.push_back(it->second);
        }

        return strV;
    }
};

76. Minimum coverage substring

Sliding window: use the left and right pointers to record the left and right boundaries. The right boundary is wide and the left boundary shrinks to obtain the minimum coverage substring. Use HashMap to record the number of characters in a string

class Solution {
public:
    unordered_map<char, int> ori, cnt;

    string minWindow(string s, string t) {
        // Count the number of words per character
        for (const auto &c : t) {
            ++ori[c];
        }

        int l = 0, r = -1;
        int len = INT_MAX, ansL = -1, check = t.length(); // Check to check that all characters have been matched
        int s_len = s.length();
        while (r < s_len) {
            // Is not a character in the pattern string
            if (ori.find(s[++r]) == ori.end()) continue;

            // Count the number of characters matched
            if (++cnt[s[r]] <= ori[s[r]]) {
                check--;
            }

            // Check that all characters have been matched
            while (!check && l <= r) {
                if (r - l + 1 < len) {
                    len = r - l + 1;  // The shortest length satisfying the condition
                    ansL = l;         // Record left boundary
                }

                // Left slip
                if (ori.find(s[l]) != ori.end()) {
                    if (--cnt[s[l]] < ori[s[l]]) ++check;
                }
                ++l;
            }
        }

        return ansL == -1 ? string() : s.substr(ansL, len);
    }
};

Topics: leetcode