LeetCode 4 寻找两个有序数组的中位数
LeetCode 4 寻找两个有序数组的中位数
官网: https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
题目描述(英文)
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
题目描述(中文)
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
提交代码
import java.util.Arrays; class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int [] arr = new int[(nums1 == null? 0:nums1.length) + (nums2 == null? 0:nums2.length)]; if(nums1 != null && nums2 != null){ System.arraycopy(nums1, 0, arr, 0, nums1.length); System.arraycopy(nums2, 0, arr, nums1.length, nums2.length); } else if(nums1 == null) System.arraycopy(nums1, 0, arr, 0, nums1.length); else System.arraycopy(nums2, 0, arr, 0, nums2.length); Arrays.sort(arr); int mid = arr.length / 2; if(arr.length % 2 == 0) return (arr[mid - 1] + arr[mid]) / 2.0; else return arr[mid]; } }
提交反馈
执行结果:通过
执行用时 :4 ms, 在所有 Java 提交中击败了97.47%的用户
内存消耗 :47.7 MB, 在所有 Java 提交中击败了92.66%的用户