You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:LeetCode排序数组问题中我的非原地归并排序代码异常

排查归并排序代码问题

我在解决LeetCode的「排序数组(Sort An Array)」问题时,自己编写的非原地归并排序代码无法正常运行,但发现一段逻辑与我的代码一致的示例代码却能完美解决该问题。

以下是这段可正常运行的示例代码:

class Solution {
private: 
    void merge(vector<int>& a, int low, int mid, int high){
        int i = low;
        int j = mid+1;
        int k = 0;
        vector<int> b(a.size(), 0);
        while(i<=mid && j<=high){
            if(a[i] <= a[j]){
                b[k] = a[i];
                i++, k++;
            }else{
                b[k] = a[j];
                j++, k++;
            }
        }
        while(i<=mid){
            b[k] = a[i];
            i++, k++;
        }
        while(j<=high){
            b[k] = a[j];
            j++, k++;
        }
        // copy b array into a array 
        i=low;
        while(i <= high){
            a[i] = b[i];
            i++;
        }
    }
    void mergeSort(vector<int>& a, int low, int high){
        if(low >= high) return;
        int mid = low + ((high - low)/2);
        mergeSort(a, low, mid);
        mergeSort(a, mid + 1, high);
        merge(a, low, mid, high);
    }
public:
    vector<int> sortArray(vector<int>& nums) {
        mergeSort(nums, 0, nums.size()-1);
        return nums;
    }
};

我不知道自己的代码哪里出错了,恳请有人帮忙排查!

内容的提问来源于stack exchange,提问作者Vinayak Chittora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 20:40:20