что не так? вот задача: Given two sorted arrays and of size and respectively, return the…
- User
что не так? вот задача: Given two sorted arrays and of size and respectively, return the median of the two sorted arrays.nums1nums2mn
The overall run time complexity should be .O(log (m+n)). Вот код: class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ for i in range (len(nums2)): t=nums2[i] nums1.append(i) nums1.sort() t=(len(nums1)//2)+1 q=(len(nums1)//2) if len(nums1)%2!=0: return (nums1[t]) else: return (nums1[q]+nums1[t])/2
- Assistant
- User
Где ошибка: class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ for i in range (len(nums2)): nums1.append(i) nums1.sort() t=(len(nums1)//2) if len(nums1)%2!=0: return (nums1[t]) else: return (nums1[t+1]+nums1[t])/2
- Assistant
The error in your code is that you are appending index
itonums1instead of appending the valuenums2[i]. Here's the corrected version of the loop that mergesnums2intonums1:pythonfor num in nums2: nums1.append(num)Also, there is a mistake when computing the median for even-length arrays. You should be averaging the numbers at indexes
tandt - 1, nottandt + 1. Remember that indices in Python are zero-based, so for a list of even length, the middle two indices aret - 1andtnottandt + 1.Here's the corrected version of the entire function:
- User
Output 2.00000 Expected 2.50000
- Assistant
I apologize for the oversight in the previous response. The correct way to compute the median, especially for an even-length merged array, should involve finding the average of the two central elements. The indices for these elements should be
(len(nums1) // 2) - 1for the lower middle element andlen(nums1) // 2for the upper middle element.Here is the corrected code that should give the expected output:
python - User
what's wrong? Example 1:
Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer. Example 2:
Input: s = "cbbd" Output: "bb" class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ ma='' for i in range (len(s)): l='' for j in range (i,len(s)): l += s[j] if l==l[::-1]: if len(l)>ma: ma=l return ma
- Assistant
Your implementation of the longest palindrome substring looks almost correct, but there's an issue with the way you are attempting to update the
mavariable:Instead of comparing
len(l) > ma, you should be comparinglen(l) > len(ma)because you need to compare the lengths of the strings, not the strings themselves.Here is the corrected version of your code:
python