81 在两个长度相等的排序数组中找到上中位数
Table of Contents

ac

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;


public class Main {
    public static Scanner sc = new Scanner(System.in);

    public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws Exception {
        int n = sc.nextInt();
        int[] a1 = new int[n];
        int[] a2 = new int[n];
        for(int i=0;i<n;i++){
            a1[i] = sc.nextInt();
        }
        for(int i=0;i<n;i++){
            a2[i] = sc.nextInt();
        }
        System.out.print(getUpMedian(n, a1, a2));
    }


    // 是否奇数
    static boolean isOdd(int val){
        if(val % 2 == 1){
            return true;
        }
        return false;
    }

    static int getUpMedian(int n, int[] a1, int[] a2){
        int left1 = 0;
        int right1 = n-1;
        int left2 = 0;
        int right2 = n-1;
        if(left1 == right1){
            return Math.min(a1[left1], a2[left2]);
        }
        if(a1[right1] < a2[left2]){
            return a1[right1];
        }else if(a2[right2] < a1[left1]){
            return a2[right2];
        }else {
            while (left1 < right1) {
                int mid1 = (right1 + left1) / 2;
                int mid2 = (right2 + left2) / 2;
                if (a1[mid1] < a2[mid2]) {
                    if (isOdd(right1 - left1 + 1)) {
                        // 包括mid在内
                        left1 = mid1;
                        right2 = mid2;
                    }else {
                        left1 = mid1 + 1;
                        right2 = mid2;
                    }
                }else if (a1[mid1] > a2[mid2]) {
                    if (isOdd(right1 - left1 + 1)) {
                        // 包括mid在内
                        left2 = mid2;
                        right1 = mid1;
                    }else {
                        left2 = mid2 + 1;
                        right1 = mid1;
                    }
                }else {
                    return a1[mid1];
                }
            }
            return Math.min(a1[left1], a2[left2]);
        }
    }

}
/*
4
1 2 3 4
3 4 5 6

3 总共有8个数,上中位数是第4小的数,所以返回3。
 */
给定两个有序数组arr1arr2,已知两个数组的长度都为N,求两个数组中所有数的上中位数。
上中位数:假设递增序列长度为n,若n为奇数,则上中位数为第n/2+1个数;否则为第n个数