1. Two Sum

Posted joannae

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1. Two Sum相关的知识,希望对你有一定的参考价值。

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

typedef struct MyNum{
    int num;
    int index;
}MyNum;

int* twoSum(int* nums, int numsSize, int target) {
    int start = 0;
    int end = numsSize-1;
    int* result = NULL;
    MyNum* myNums;
    int sum;
    
    if(numsSize < 2) return result;
    
    result = malloc(sizeof(int)*2);
    myNums = malloc(sizeof(MyNum)*numsSize);
    for(int i = 0; i < numsSize; i++){
        myNums[i].num = nums[i];
        myNums[i].index = i;
    }
    
    quickSort(myNums, start, end);

    sum = myNums[start].num+myNums[end].num;
    while(sum != target){
        if(sum > target) end--;
        else start++;
        sum = myNums[start].num+myNums[end].num;
    }
    
    if(myNums[start].index <= myNums[end].index){
        result[0] = myNums[start].index;
        result[1] = myNums[end].index;
    }
    else{
        result[1] = myNums[start].index;
        result[0] = myNums[end].index;
    }
    return result;
}

void quickSort(MyNum* nums, int start, int end){
    int p1 = start+1; 
    int p2 = end;
    MyNum tmp;

    while(p1 <= p2){
        while(p1 <= p2 && nums[p1].num <= nums[start].num ){
            p1++;
        }
        while(p1 <= p2 && nums[p2].num > nums[start].num ){
            p2--;
        }
        if(p1 < p2){
            tmp = nums[p1];
            nums[p1] = nums[p2];
            nums[p2] = tmp;
            p1++;
            p2--;
        }
    }

    //put the sentinel at the end of the first subarray
    if(start!=p2){
    tmp = nums[start];
    nums[start] = nums[p2];
    nums[p2] = tmp;
    }
            
    if(start < p2-1) quickSort(nums,start, p2-1); //sort first subarray (<=sentinel)
    if(p1 < end) quickSort(nums,p1, end); //sort second subarray  (>sentinel)
}

 

以上是关于1. Two Sum的主要内容,如果未能解决你的问题,请参考以下文章

1_Two Sum --LeetCode

Two Sum

每日一算法之two sum

LeetCode之371. Sum of Two Integers

Two Sum

1. Two Sum