[leetcode hot questions 100] Question record (1-4)

1. The sum of two numbers

Question link

Given an integer array numsand an integer target value target, please find the two integers in the array whose sum is the target value targetand return their array subscripts.

You can assume that each input will correspond to only one answer. However, the same element in the array cannot appear repeatedly in the answer.

You can return answers in any order.

Insert image description here

 
 
Answers to questions

The idea is to use num-targetit as a dictionary key, and then record the corresponding subscripts. When a number is found, just return the corresponding two indexes directly.

python answer

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = dict()
        for i, num in enumerate(nums):
            if num not in dic:
                dic[target - num] = i
            else:
                return [dic[num], i]

cpp answer

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

        return {
    
    };

    }
};

2. Add two numbers

Question link

You are given two non-empty linked lists, representing two non-negative integers. Each of their digits is stored in reverse order, and each node can only store one digit.

Please add two numbers and return a linked list representing the sum in the same form.

You can assume that except for the number 0, neither number will start with a 0.

Insert image description here

 
 
Answers to questions

Just simulate it directly. When using C++, pay attention to whether the returned object is a pointer or an object. If it is a pointer, use it instead of an ->object ..

python answer

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        adds = 0 # 进位
        head = curr = ListNode(0)
        while l1 or l2 or adds:
            val = 0
            if l1: 
                val += l1.val
                l1 = l1.next
            if l2: 
                val += l2.val
                l2 = l2.next
            val, adds = (val + adds) % 10, (val + adds) // 10 
            node = ListNode(val)
            curr.next = node
            curr = curr.next
        return head.next

cpp answer

class Solution {
    
    
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    
    
        int adds = 0;
        ListNode *head = nullptr;
        ListNode *curr = nullptr;
        head = curr = new ListNode(0);
        while (l1 || l2 || adds)
        {
    
    
            int val = 0;
            if(l1)
            {
    
    
                val += l1->val;
                l1 = l1->next;
            }
            if(l2)
            {
    
    
                val += l2->val;
                l2 = l2->next;
            }
            curr->next = new ListNode((val + adds) % 10);
            adds = (val + adds) / 10;
            curr = curr->next;
        }
        return head->next;
    }
};

3. The longest substring without repeated characters

Question link

Given a string s, please find 不含有重复字符the .最长子串长度

Insert image description here

 
 
Answers to questions

Double pointer plus set

Sliding the window from left to right. If you encounter setan element that is not there, the right pointer keeps moving to the right until it is no longer satisfied. Update the longest distance, then add s[r]and delete s[l]. I also recorded it here final_l, which is equivalent to if the longest distance is required. If the subsequence is not repeated, then output it directly.s[final_l:final_l+res]

python answer

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        l, r = 0, 0
        final_l = 0
        res = 0
        dic = set()
        while r < len(s):
            while r < len(s) and s[r] not in dic:
                dic.add(s[r])
                r += 1
            if r - l > res:
                res = r - l
                final_l = l
            dic.remove(s[l])
            l += 1
        return res

cpp answer

class Solution {
    
    
public:
    int lengthOfLongestSubstring(string s) {
    
    
        int l = 0, r = 0, res = 0, final_l;
        unordered_set<char> dic;
        while (r < s.size())
        {
    
    
            while (r < s.size() and dic.find(s[r]) == dic.end())
            {
    
    
                dic.insert(s[r]);
                r ++;
            }

            if (r - l > res)
            {
    
    
                res = r - l;
                final_l = l;
            }

            dic.erase(s[l]);
            l ++;

        }
        return res;
    }
};

4. Find the median of two positive arrays

Question link

Given two positively ordered (from small to large) arrays and of sizes mand respectively . Please find and return these two positive-order arrays .nnums1nums2中位数

The time complexity of the algorithm should be O(log (m+n)).

Insert image description here

 
 
Answers to questions

二分查找

Specifically, it is to find a division of two arrays and transform it into a problem of finding the first k small numbers. When dividing, it is mainly to make the values ​​of the elements on the left and right of the dividing line satisfy the intersection order relationship, and then discuss some boundary conditions. For details, please see the official website analysis

python answer

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        if len(nums1) > len(nums2):
            return self.findMedianSortedArrays(nums2, nums1)

        infinty = 2**40
        m, n = len(nums1), len(nums2)
        left, right = 0, m
        # median1:前一部分的最大值
        # median2:后一部分的最小值
        median1, median2 = 0, 0

        while left <= right:
            # 前一部分包含 nums1[0 .. i-1] 和 nums2[0 .. j-1]
            # // 后一部分包含 nums1[i .. m-1] 和 nums2[j .. n-1]
            i = (left + right) // 2
            j = (m + n + 1) // 2 - i

            # nums_im1, nums_i, nums_jm1, nums_j 分别表示 nums1[i-1], nums1[i], nums2[j-1], nums2[j]
            nums_im1 = (-infinty if i == 0 else nums1[i - 1])
            nums_i = (infinty if i == m else nums1[i])
            nums_jm1 = (-infinty if j == 0 else nums2[j - 1])
            nums_j = (infinty if j == n else nums2[j])

            if nums_im1 <= nums_j:
                median1, median2 = max(nums_im1, nums_jm1), min(nums_i, nums_j)
                left = i + 1
            else:
                right = i - 1

        return (median1 + median2) / 2 if (m + n) % 2 == 0 else median1

cpp answer

class Solution {
    
    
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    
    
        if (nums1.size() > nums2.size()) {
    
    
            return findMedianSortedArrays(nums2, nums1);
        }
        
        int m = nums1.size();
        int n = nums2.size();
        int left = 0, right = m;
        // median1:前一部分的最大值
        // median2:后一部分的最小值
        int median1 = 0, median2 = 0;

        while (left <= right) {
    
    
            // 前一部分包含 nums1[0 .. i-1] 和 nums2[0 .. j-1]
            // 后一部分包含 nums1[i .. m-1] 和 nums2[j .. n-1]
            int i = (left + right) / 2;
            int j = (m + n + 1) / 2 - i;

            // nums_im1, nums_i, nums_jm1, nums_j 分别表示 nums1[i-1], nums1[i], nums2[j-1], nums2[j]
            int nums_im1 = (i == 0 ? INT_MIN : nums1[i - 1]);
            int nums_i = (i == m ? INT_MAX : nums1[i]);
            int nums_jm1 = (j == 0 ? INT_MIN : nums2[j - 1]);
            int nums_j = (j == n ? INT_MAX : nums2[j]);

            if (nums_im1 <= nums_j) {
    
    
                median1 = max(nums_im1, nums_jm1);
                median2 = min(nums_i, nums_j);
                left = i + 1;
            } else {
    
    
                right = i - 1;
            }
        }

        return (m + n) % 2 == 0 ? (median1 + median2) / 2.0 : median1;
    }
};

Guess you like

Origin blog.csdn.net/qq_36306288/article/details/124877948