3ms accepted solution with C using qsort(), easy to understand


  • 1
    A
    int* twoSum(int* nums, int numsSize, int target) {
        
        int cmp(const void* a, const void* b){
        return *(int*)a - *(int*)b;
        }
        
        int* ans = NULL;
        int* copy = NULL;
        int low = 0;
        int high = numsSize - 1;
        int key1,key2 = 0;
        int i;
        copy = (int*)malloc(numsSize*sizeof(int));
        for(i = 0;i < numsSize;i++){
            copy[i] = nums[i];
        }
        ans = (int*)malloc(2 * sizeof(int));
        qsort(copy,numsSize,sizeof(int),cmp);
    
        while(low < high){
            if(copy[low] + copy[high] > target) high--;
            else if(copy[low] + copy[high] < target) low++;
            else {
                key1 = copy[low];
                key2 = copy[high];
                i = 0;
                while(i < numsSize){
                    if(nums[i] == key1 || nums[i] == key2){
                        ans[0] = i;
                        i++;
                        break;
                    }
                    else i++;
                }
                while(i < numsSize){
                    if(nums[i] == key1 || nums[i] == key2){
                        ans[1] = i;
                        i++;
                        break;
                    }
                    else i++;
                }
                free(copy);
                return ans;
            }
        }
        free(copy);
        return NULL;
    }
    

Log in to reply
 

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