[关闭]
@CrazyHenry 2018-01-01T09:45:55.000000Z 字数 2134 阅读 1310

Leetcode4. Median of Two Sorted Arrays

ddddLeetcode刷题


38724-106.jpg-521.4kB

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

我的代码1:时间复杂度O(nlogn)~O(n^2),空间复杂度O(n)

IMG_20171210_095716.jpg-2529.6kB

  1. //Author: Li-Yingmin@https://liyingmin.wixsite.com/henry
  2. //Email: li_yingmin@outlook.com
  3. //Leetcode-4
  4. //T(n)=O(nlogn)~O(n^2), S(n)=O(n)
  5. class Solution {
  6. public:
  7. double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
  8. if(0 == nums1.size() + nums2.size()) return -1;
  9. nums1.insert(nums1.end(),nums2.begin(),nums2.end());
  10. sort(nums1.begin(),nums1.end());//排序,时间复杂度高,代价昂贵
  11. if(nums1.size() % 2 != 0)//奇数
  12. return nums1[nums1.size()/2];
  13. else return (nums1[nums1.size()/2] + nums1[nums1.size()/2 - 1])/2.0;
  14. }
  15. };

image.png-85.7kB

我的代码2:时间复杂度O(k)~O(m+n),空间O(1)

image.png-193.9kB

  1. //Author: Li-Yingmin@https://liyingmin.wixsite.com/henry
  2. //Email: li_yingmin@outlook.com
  3. //Leetcode-4
  4. //T(n)=O(k)~O(m+n), S(n)=O(1)
  5. class Solution {
  6. public:
  7. double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
  8. auto midsize = (nums1.size() + nums2.size()) / 2;
  9. decltype(nums1.size()) temp = 0;//游标
  10. int value = 0;
  11. int medianL = 0;
  12. int medianR = 0;
  13. auto vit1 = nums1.begin();
  14. auto vit2 = nums2.begin();
  15. while(vit1 != nums1.end() || vit2 != nums2.end())
  16. {
  17. if(vit2 == nums2.end() || (vit1 != nums1.end() && *vit1 <= *vit2))
  18. {
  19. value = *vit1;
  20. ++vit1;
  21. }
  22. else
  23. {
  24. value = *vit2;
  25. ++vit2;
  26. }
  27. if(midsize != 0 && temp == midsize - 1)//如果midsize=0,这里不安全
  28. medianL = value;
  29. if(temp == midsize)
  30. {
  31. medianR = value;
  32. break;
  33. }
  34. ++temp;
  35. }
  36. if((nums1.size() + nums2.size()) % 2 != 0) return medianR;
  37. else return (medianL + medianR)/2.0;
  38. }
  39. };

image.png-143.7kB

优秀代码:时间复杂度O(log(m+n)),空间O(1)?

image.png-318.1kB

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注