Detailed explanation of LLEETCODE: 4. Find the median of two positive sequence arrays; 5. The longest palindrome substring

Title: Finding the Median of Two Ordinal Arrays

topic:

Given two positive order (from small to large) arrays nums1 and nums2 of size m and n respectively. Please find and return the median of these two ordinal arrays.

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

Example 1:

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: Combined array = [1,2,3], median 2
Example 2:

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: Combined array = [1,2,3,4], median (2 + 3) / 2 = 2.5

Code answer:

class Solution {

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {

        // Get the length of nums1 and nums2

        int m = nums1.length;

        int n = nums2.length;

        // Merge nums1 and nums2, equal in length and equal in value;

        double[] z = new double[m + n];

        for(int i = 0; i < m; i++) z[i] = nums1[i];

        for(int i = m, j = 0; i < m + n; i++, j++) z[i] = nums2[j];

        // Introduce the sort function to automatically arrange the new array in ascending order from small to large

        Arrays.sort(z);

        // According to the parity of the merged array length, output the median of the new array

        if((m + n) % 2 == 0) return (z[(m + n) / 2 - 1] + z[(m + n) / 2]) / 2;

        else return z[(m + n) / 2];

    }

}

Title:  Longest Palindromic Substring

topic:

Given a string s, find the longest palindromic substring in s.

Example 1:

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also the answer to the question.
Example 2:

Input: s = "cbbd"
Output: "bb"
 

hint:

1 <= s.length <= 1000
s consists of numbers and letters only

Code answer:

class Solution { public String longestPalindrome(String s) { int max =0; String res = new String();//create a new result string //traverse each position for(int i=0;i<s.length ();i++){ //The center may be 1 character or 2 characters for(int j=0;j<=1;j++){ int l = i; int r = i + j; //Left side The index is greater than 0, the index on the right is less than the total length of the string, and the characters corresponding to the left and right index mappings are equal while(l>=0&&r<s.length()&&s.charAt(l)==s.charAt(r)){ if((r-l+1)>max){ max = rl +1; res = s.substring(l,r+1);//Intercept from the lth character on the left to the r+1th character char } l--; r++; } } } return res; } }






















Some screenshots during the questioning process:

 

Supongo que te gusta

Origin blog.csdn.net/Abtxr/article/details/126305398
Recomendado
Clasificación