LeetCode : Median of Two Sorted Arrays [java]

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

思路:类似于归并排序,找到一半的排好序的序列,最后一个(或最后两个数的平均数)即为所求,注意边界条件检查即可。


import java.util.ArrayList;

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    	ArrayList<Integer> list = new ArrayList<>();
		int length1 = nums1.length;
		int length2 = nums2.length;
		int count = length1 + length2;

		if (length1 == 0 && length2 == 0) {
			return 0;
		}
		if (length1 == 0) {
			if (length2 % 2 == 0) {
				return (nums2[length2 / 2 - 1] + nums2[length2 / 2]) / 2.0;
			} else {
				if (length2 == 1) {
					return nums2[0];
				} else {
					return nums2[length2 / 2];
				}
			}
		}
		if (length2 == 0) {
			if (length1 % 2 == 0) {
				return (nums1[length1 / 2 - 1] + nums1[length1 / 2]) / 2.0;
			} else {
				if (length1 == 1) {
					return nums1[0];
				} else {
					return nums1[length1 / 2];
				}
			}
		}
		int medianIndex = count / 2;
		int index1 = 0;
		int index2 = 0;
		for (int i = 0; i <= medianIndex; i++) {
			if (index1 < length1 && index2 < length2) {
				if (nums1[index1] < nums2[index2]) {
					list.add(nums1[index1]);
					index1++;
				} else {
					list.add(nums2[index2]);
					index2++;
				}
			} else if (index1 < length1) {
				list.add(nums1[index1]);
				index1++;
			} else if (index2 < length2) {
				list.add(nums2[index2]);
				index2++;
			}
		}

		if (count % 2 == 0) {
			int num1 = list.get(list.size() - 2);
			int num2 = list.get(list.size() - 1);
			return (num1 + num2) / 2.0;
		} else {
			return list.get(list.size() - 1);
		}
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值