[关闭]
@ysner 2021-10-26T05:54:20.000000Z 字数 1842 阅读 684

LeetCode4—寻找两个正序数组的中位数

顺序表 查找


第一次提交的代码:(归并排序)

  1. class Solution {
  2. public double findMedianSortedArrays(int[] nums1, int[] nums2) {
  3. int[] num=new int[3000];
  4. int head1,head2,head,m=nums1.length,n=nums2.length;//求数组长度:.length就可,不要括号!!!
  5. head1=head2=head=0;
  6. while(head1<m&&head2<n)
  7. {
  8. if(nums1[head1]>nums2[head2])
  9. {
  10. num[head]=nums2[head2];
  11. head++;
  12. head2++;
  13. }
  14. else
  15. {
  16. num[head]=nums1[head1];
  17. head++;
  18. head1++;
  19. }
  20. }
  21. while(head1<m)
  22. {
  23. num[head]=nums1[head1];
  24. head++;
  25. head1++;
  26. }
  27. while(head2<n)
  28. {
  29. num[head]=nums2[head2];
  30. head++;
  31. head2++;
  32. }
  33. int t=(n+m)/2;
  34. return ((n+m)%2==1)?num[t]:((num[t-1]+num[t])/2.0); //注意想的是第n个数,写的编号是n-1
  35. }
  36. }

第二次提交的代码:(归并排序+常数优化)

  1. class Solution {
  2. public double findMedianSortedArrays(int[] nums1, int[] nums2) {
  3. int head1,head2,head,m=nums1.length,n=nums2.length,t,Now=0,Las=0;
  4. head1=head2=head=0;
  5. t=(n+m)/2;
  6. boolean tag=((n+m)%2==1);
  7. while(head1<m&&head2<n)
  8. {
  9. if(nums1[head1]>nums2[head2])
  10. {
  11. Las=Now;Now=nums2[head2];
  12. if(head==t) return tag?Now:((Now+Las)/2.0);
  13. head++;head2++;
  14. }
  15. else
  16. {
  17. Las=Now;Now=nums1[head1];
  18. if(head==t) return tag?Now:((Now+Las)/2.0);
  19. head++;head1++;
  20. }
  21. }
  22. while(head1<m)
  23. {
  24. Las=Now;Now=nums1[head1];
  25. if(head==t) return tag?Now:((Now+Las)/2.0);
  26. head++;head1++;
  27. }
  28. while(head2<n)
  29. {
  30. Las=Now;Now=nums2[head2];
  31. if(head==t) return tag?Now:((Now+Las)/2.0);
  32. head++;head2++;
  33. }
  34. return -1;
  35. }
  36. }

第三次提交的代码:(二分查找)

  1. class Solution {
  2. public double findMedianSortedArrays(int[] nums1, int[] nums2) {
  3. if(nums1.length>nums2.length)
  4. {
  5. int[] tmp=nums1;
  6. nums1=nums2;
  7. nums2=tmp;//用小数组二分,减小二分范围
  8. }
  9. int m=nums1.length,n=nums2.length;
  10. int tot=(n+m+1)/2;
  11. int L=0,R=m;//二分nums1出了多少个数,结果为L
  12. while(L<R)
  13. {
  14. int mid=(L+R+1)/2,j=tot-mid;//二分注意:不加1的话会在R-L=1时出死循环
  15. if(nums1[mid-1]<=nums2[j]) L=mid;
  16. else R=mid-1;
  17. }
  18. int i=L,j=tot-i;
  19. int s1L=(i==0)?Integer.MIN_VALUE:nums1[i-1],
  20. s1R=(i==m)?Integer.MAX_VALUE:nums1[i],
  21. s2L=(j==0)?Integer.MIN_VALUE:nums2[j-1],
  22. s2R=(j==n)?Integer.MAX_VALUE:nums2[j];//特殊处理分割线恰好在数组边界的情况
  23. if((n+m)%2==1) return Math.max(s1L,s2L);
  24. else return (Math.max(s1L,s2L)+Math.min(s1R,s2R))/2.0;
  25. }
  26. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注