合并排序阵列的中间返回错误的值
目标是合并两个排序的阵列,并返回中位数(双重)。
我正在创建一个较大的大小 nums1+nums2 在迭代时,将较小元素的值添加到大数组中。 保留每个给定的指针。
我无法分辨我的数组是否被填充,并且在大多数情况下它返回0,而其他人则“除以0”错误;
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len = nums1.length+nums2.length;
int[] nums = new int[len];
int pone=0;
int ptwo=0;
double ans;
for(int i=0;i>nums.length;i++){
if(pone==nums1.length) nums[i] = nums2[ptwo++];
else if(ptwo==nums2.length) nums[i] = nums1[pone++];
if(nums1[pone]<nums2[ptwo] && pone<nums1.length){
nums[i]=nums1[pone];
pone++;
}else if(nums1[pone]>nums2[ptwo] && ptwo<nums2.length){
nums[i] = nums2[ptwo];
ptwo++;
}
System.out.print(nums[i]);
}
if(len%2==0) ans = nums[len/2] / nums[(len/2)-1];
else ans = nums[len/2];
return ans;
}
}
The goal is to merge two sorted arrays, and return a median(double).
I am creating a larger array of size nums1+nums2
and while iterating through, adding the value of the smaller element into the large array.
keeping pointers for each given one.
I cannot tell if my array is being populated, and it is returning 0 for most cases, and "divide by 0" error for others;
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len = nums1.length+nums2.length;
int[] nums = new int[len];
int pone=0;
int ptwo=0;
double ans;
for(int i=0;i>nums.length;i++){
if(pone==nums1.length) nums[i] = nums2[ptwo++];
else if(ptwo==nums2.length) nums[i] = nums1[pone++];
if(nums1[pone]<nums2[ptwo] && pone<nums1.length){
nums[i]=nums1[pone];
pone++;
}else if(nums1[pone]>nums2[ptwo] && ptwo<nums2.length){
nums[i] = nums2[ptwo];
ptwo++;
}
System.out.print(nums[i]);
}
if(len%2==0) ans = nums[len/2] / nums[(len/2)-1];
else ans = nums[len/2];
return ans;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论