Loading

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

题目地址:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/

难度:困难

基本思路:

  • 将两个有序链表合并,然后根据中位数定义查找
  • 分段折半查找

合并链表(low的一笔)

public class Solution {
    public static void main(String[] args) {
        Solution s = new Solution();
        double ans = s.findMedianSortedArrays(new int[]{1,3,4}, new int[]{2});
        System.out.println(ans);
    }
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        // 双指针合并数组
        int len1 = nums1.length, len2 = nums2.length, n = len1 + len2;
        int[] res = new int[n];
        int p = 0, q = 0, k = 0;
        if(len1 == 0 && len2 != 0){
            res = nums2;
        }else if(len1 != 0 && len2 == 0){
            res = nums1;
        }else {
            while (p < len1 && q < len2) {
                if (nums1[p] > nums2[q]) {
                    res[k++] = nums2[q++];
                } else if (nums1[p] == nums2[q]) {
                    res[k++] = nums2[q++];
                    res[k++] = nums1[p++];
                } else {
                    res[k++] = nums1[p++];
                }
            }
            while (p < len1) {
                res[k++] = nums1[p++];
            }
            while (q < len2) {
                res[k++] = nums2[q++];
            }
            int i = 0;
            while (i++ < res.length) {
                System.out.print(res[i - 1] + ",");
            }
        }
        if (res.length % 2 == 0) {
            return (double) (res[res.length / 2] + res[(res.length / 2) - 1]) / 2;
        } else {
            return (double) res[(res.length - 1) / 2];
        }
    }
}

分段折半查找(今天没想明白,想出来更新)

 

posted @ 2021-04-12 15:11  BigBender  阅读(39)  评论(0编辑  收藏  举报