写在前面:在LeetCode上做的题,代码基本都是我自己写的,效率有好有坏,仅供参考。
有少数几道题苦思冥想做不出来的,可能会借鉴网上大神的解法,然后再自己编写,借鉴过他人解法的题会有说明。
本人不是算法出身,语言基本靠自学,有任何错误理解或者不当举措,还请各位大侠手下留情并不吝赐教!万分感谢~
题:
4. Median of Two Sorted Arrays
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)).
Example 1:
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
解题思路:
这道题标的难度是hard,但我做完感觉还行,并没有无从下手的感觉。从题目的叙述也感觉只是个简单的中位数的问题而已,并没有什么坑。
拿到这道题,立马就想到合并,然后就感觉已经做完了{摊手}。
先上代码:
1 class Solution { 2 3 public double findMedianSortedArrays(int[] nums1, int[] nums2) { 4 5 int[] nums = addTwo(nums1,nums2); 6 return this.count(nums); 7 } 8 9 public int[] addTwo(int[] nums1,int[] nums2){ 10 11 int[] nums = new int[nums1.length+nums2.length]; 12 int s = 0; 13 int i = 0; 14 int j = 0; 15 while(i<nums1.length||j<nums2.length) { 16 if(i==nums1.length&&j<nums2.length) { 17 for(;j<nums2.length;j++,s++){ 18 nums[s] = nums2[j]; 19 } 20 }else if(i<nums1.length&&j==nums2.length) { 21 for(;i<nums1.length;i++,s++) { 22 nums[s] = nums1[i]; 23 } 24 }else { 25 if(nums1[i]<nums2[j]) { 26 nums[s] = nums1[i]; 27 i++; 28 s++; 29 } 30 else { 31 nums[s] = nums2[j]; 32 j++; 33 s++; 34 } 35 } 36 } 37 return nums; 38 } 39 40 public double count(int[] nums){ 41 if(nums.length%2==0) return (nums[nums.length/2]+nums[nums.length/2-1])/2.0; 42 else return nums[nums.length/2]; 43 } 44 }
方法addTwo就是将题目中的nums1和nums2合并成nums。因为题目中提到,是two sorted arrays,既然已经排好序了,那更没有不合并的道理了(也是我没有更好的想法,只能想到这个)。。。很简单的对比,因为是已经排好序的,两个数组挨个从前到后对比就行了,然后从小到大存入nums中。
排好序之后,只需要找到中位数即可。。。奇数的话直接找nums.length/2即可,偶数的话就返回(nums[nums.length/2]+nums[nums.length/2-1])/2.0。注意这里/2.0可以让结果自动转成double,/2的话java会自动四舍五入,与答案不符。
运行时间68ms,结果一般,但思路比较清晰,也很容易理解。以后有时间再研究下更加效率的解法:)

浙公网安备 33010602011771号