What's wrong in my code? The run result is right in my own computer.


  • 0
    Y

    `
    void swap(int *a, int *b)
    {
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
    }
    int partition(int a[], int p, int r)
    {
    int x = a[r];
    int i = p - 1;
    for (int j = p; j<r; j++)
    {
    if (a[j] <= x)
    {
    i++;
    swap(&a[j], &a[i]);
    }
    }
    swap(&a[i + 1], &a[r]);
    return i + 1;
    }
    void quickSort(int a[], int p, int r)
    {
    if (p<r)
    {
    int q = partition(a, p, r);
    quickSort(a, p, q - 1);
    quickSort(a, q + 1, r);
    }
    }

    int myBinarySearch(int a[], int low, int high, int key)
    {
    while (low <= high)
    {
    int middle = (low + high) / 2;
    if (a[middle] == key)
    {
    return middle;
    }
    else if (a[middle]>key)
    {
    high = middle - 1;
    }
    else
    {
    low = middle + 1;
    }
    }
    return -1;
    }

    int* twoSum(int* nums, int numsSize, int target, int* returnSize)
    {
    returnSize = NULL;
    if (numsSize <= 2)
    {
    return returnSize;
    }
    int index[2] = { -1, -1 };
    int arr[1000] = {0};
    for (int k = 0; k<numsSize; k++)
    {
    arr[k]= nums[k];
    }

    quickSort(arr, 0, numsSize - 1);
    
    int key = 0;
    int i = 0;
    int pos = -1;
    while (i < numsSize - 2)
    {
    	key = target - arr[i];
    	pos = myBinarySearch(arr, i + 1, numsSize - 1, key);
    	if (pos != -1)
    	{
    		break;
    	}
    	i++;
    }
    
    if (pos != -1)
    {
    	for (int m = 0; m<numsSize; m++)
    	{
    		if (nums[m] == arr[i])
    		{
    			index[0] = m + 1;
    			break;
    		}
    	}
    	for (int n = 0; n<numsSize ; n++)
    	{
    		if (nums[n] == arr[pos])
    		{
    			index[1] = n + 1;
    			break;
    		}
    	}
    	if (index[0]>index[1])
    	{
    		swap(&index[0], &index[1]);
    	}
    	returnSize = index;
    }
    return returnSize;
    

    }
    `


Log in to reply
 

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