合并排序阵列的中间返回错误的值

发布于 2025-01-31 12:55:52 字数 1074 浏览 1 评论 0原文

目标是合并两个排序的阵列,并返回中位数(双重)。

我正在创建一个较大的大小 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文