A runtime error C implementation


  • 0
    C

    I think the following two implementations based on C++ and C are almost the same.
    The first C++ imp works fine with 18 ms.
    However, the C imp encounter the runtime error.
    Does there anybody know the reason?
    Thanks a lot!

    ===== C++ =====

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            vector<int> ret(2, -1);
            int i=0, j = nums.size() - 1;
            while(i < j) {
                int mid = (i + j) / 2;
                if(nums.at(mid) < target) {
                    i = mid + 1;
                }
                else {
                    j = mid;
                }
            }
            if(nums.at(i) != target) {
                return ret;
            }
            else {
                ret[0] = i;
                j = nums.size() - 1;
            }
            while(i < j) {
                int mid = (i + j) / 2 + 1;
                if(nums.at(mid) > target) {
                    j = mid - 1;
                }
                else {
                    i = mid;
                }
            }
            ret[1] = j;
            return ret;
        }
    };
    

    ===== C =====

    int* searchRange(int* nums, int numsSize, int target, int* returnSize) {
        returnSize[0] = returnSize[1] = -1;
        int i = 0, j = numsSize-1;
        while(i < j) {
            int mid = (i + j) / 2;
            if(nums[mid] < target) {
                i = mid + 1;
            }
            else {
                j = mid;
            }
        }
        if(nums[i] != target) {
            return returnSize;
        }
        else {
            returnSize[0] = i;
            j = numsSize-1;
        }
        while(i < j) {
            int mid = (i + j) / 2 + 1;
            if(nums[mid] > target) {
                j = mid - 1;
            }
            else {
                i = mid;
            }
        }
        returnSize[1] = j;
        return returnSize;
    }
    

    =====

    BTW, I have no idea about the difference between the argument returnSize and return int pointer.
    Anyway, I suppose I have to return the result by returnSize.

    Thanks for your help!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.