• 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];
            }
        }
    }

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

    论读书
    睁开眼,书在面前
    闭上眼,书在心里
  • 相关阅读:
    View转化为bitmap
    Bitmap 与Drawable相互转换
    android studio 连接不到真机
    解决Android sync无法同步问题
    Stetho管理手机
    android sugar no such table
    android 建数据库的正确写法
    android JSON 数据解析
    android notification 理解
    android aidl 简单使用
  • 原文地址:https://www.cnblogs.com/YC-L/p/14648126.html
Copyright © 2020-2023  润新知