I couldn't find the bug after 3 days, I need help


  • 0
    L
    /**
     * Return an array of size *returnSize.
     * Note: The returned array must be malloced, assume caller calls free().
     */
    
    void quickSort(int* arr, int low, int high) {
        if (low < high) {
            int temp = arr[low];
            int i = 0, j = high;
            while (i < j) {
                while (i < j && arr[j] >= temp) --j;
                if (i < j) arr[i++] = arr[j];
                while (i < j && arr[i] <= temp) ++i;
                if (i < j) arr[j--] = arr[i];
            }
            arr[i] = temp;
            quickSort(arr, low, i-1);
            quickSort(arr, i+1, high);
        }
    } 
    
    int binarySearch(int * arr, int low, int high, int key){
        int mid;
        while (low <= high) {
            mid = (low + high) / 2;
            if (arr[mid] == key) return mid;
            else if (arr[mid] > key) high = mid - 1;
            else low = mid + 1;
        }
        return -1;
    }
    
    int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
        int * arr1, *arr2; int len1, len2;
        if (nums1Size < nums2Size) {
            len1 = nums1Size; len2 = nums2Size;
            arr1 = nums1; arr2 = nums2;
        } else {
            len1 = nums2Size; len2 = nums1Size;
            arr2 = nums1; arr1 = nums2;
        }
        
        bool * visit = (bool *) malloc (len1 * sizeof(bool));
        int * an = (int *) malloc (len1 * sizeof(int));
        *returnSize = 0;
        
        quickSort(arr1, 0, len1 - 1);
        
        int index, L = 0;
        for (int k = 0; k < len2; ++k) {
            index = binarySearch(arr1, 0, len1 - 1, arr2[k]);
            if (index != -1) {
                if (!visit[index]) {
                    visit[index] = true;
                    an[L++] = arr2[k];
                }
            }
        }
        *returnSize = L;
        int * res = (int *) malloc(L * sizeof(int));
        while (--L >= 0) res[L] = an[L];
        free(visit); free(an);
        return res;
    }
    

  • 0
    L

    @Lairai
    It is prompted that run-time error occurred, but I found nothing wrong logically.


Log in to reply
 

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