赞
踩
起源是做查找两个有序数组的中位数用了python和java.
如果用下面的python代码就会出现list indices must be integers or slices, not float
class Solution: def findMedianSortedArrays(self, nums1, nums2): m, n = len(nums1), len(nums2) if m>n: nums1, nums2, m, n = nums2, nums1, n, m if n==0: raise ValueError imin, imax, halflen = 0, m, (m+n+1)/2 while imin<=imax: i = (imin + imax)/2 j = halflen - i if i < m and nums2[j-1] > nums1[i]: imin = i+1 elif i>0 and nums1[i-1]>nums2[j]: imax = i-1 else: if i==0: maxleft = nums2[j-1] elif j==0: maxleft = nums1[i-1] else: maxleft = max(nums1[i-1], nums2[j-1]) if (m+n)%2==1: return maxleft if i==m: minright = nums2[j] elif j==n: minright = nums1[i] else: minright = min(nums1[i], nums2[j]) return (maxleft+minright)/2.0
原因是python2和3的不同,在python3中,使用“/”进行运算会得到一个浮点数,那么在用这个作为索引的时候,会出现比如nums1[0.5]这样的情况,显然是不能查找到的。所以在python3中,这里需要用“//”,得到的才是int。正确的python代码如下:
class Solution: def findMedianSortedArrays(self, nums1, nums2): m, n = len(nums1), len(nums2) if m>n: nums1, nums2, m, n = nums2, nums1, n, m if n==0: raise ValueError imin, imax, halflen = 0, m, (m+n+1)//2 while imin<=imax: i = (imin + imax)//2 j = halflen - i if i < m and nums2[j-1] > nums1[i]: imin = i+1 elif i>0 and nums1[i-1]>nums2[j]: imax = i-1 else: if i==0: maxleft = nums2[j-1] elif j==0: maxleft = nums1[i-1] else: maxleft = max(nums1[i-1], nums2[j-1]) if (m+n)%2==1: return maxleft if i==m: minright = nums2[j] elif j==n: minright = nums1[i] else: minright = min(nums1[i], nums2[j]) return (maxleft+minright)/2.0
java代码如下:
class Solution { public double findMedianSortedArrays(int[] A, int[] B) { int m = A.length; int n = B.length; if (m>n){ int[] temp = A; A = B; B = temp; int tmp = m; m = n; n = tmp; } int imin = 0, imax=m, halflen = (m+n+1)/2; while(imin<=imax){ int i = (imin+imax)/2; int j = halflen-i; if(i<imax && B[j-1]>A[i]){ imin = i+1; } else if(i>imin && A[i-1]>B[j]){ imax = i-1; } else{ int maxleft = 0; if(i==0) {maxleft = B[j-1];} else if(j==0) {maxleft=A[i-1];} else{ maxleft = Math.max(A[i-1],B[j-1]); } if( (m+n) % 2 == 1 ) {return maxleft;} int minright = 0; if (i == m) { minright = B[j]; } else if (j == n) { minright = A[i]; } else { minright = Math.min(B[j], A[i]); } return (maxleft + minright) / 2.0; } } return 0.0; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。