LeetCode 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, and you may not use the same element twice.

Example:

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

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



1,暴力破解

int* twosum(int* nums, int numsSize, int target) { 
    int i,j; 
    int *a = (int*) malloc(2 * sizeof(int)); 
    for(i = 0;i < numsSize;i++) 
    { 
        for(j = 0;j < numsSize;j++)
       { 
            if(((nums[i] + nums[j]) == target) && (i != j)) 
            { 
                a[0] = i; 
                a[1] = j; 
                return a; 
            }
        } 
    } 
    return 0; 
} 

2,测试函数

int main(int argc, const char * argv[]) 
{ 
    std::cout << "Hello, World!\n"; 
    int input[3] = {3,2,4}; 
    int *output = (int*)malloc(2 * sizeof(int)); 
    output = twosum(input,3,6); 
    std::cout << "o1 = "<<output[0]<<std::endl; 
    std::cout << "o2 = "<<output[1]<<std::endl; 
    free(output); 
    return 0; 
}   

 3,Hash

该题时间复杂度最优解还是使用Hash表,欲输出的索引号为value,本身值为key。利用差值缩小哈希表的范围。

int* twoSum(int* nums, int numsSize, int target) {  
    int min = 0x7FFF;
    int i;
    for(i = 0;i < numsSize;i++)
    {
        if(nums[i] < min)
        {
            min = nums[i];
        }
    }
    int max = target - min;
    int len = max - min + 1;
    int *index = (int*)malloc(2 * sizeof(int));
    int *table = (int*)malloc(len * sizeof(int));
    for(i = 0;i < len;i++)
    {
        table[i] = -1;
    }
    for(i = 0;i < numsSize;i++)
    {
        if(nums[i] - min < len)
        {
            if(table[target - nums[i] - min] != -1)
            {
                index[0] = table[target - nums[i] - min];
                index[1] = i;
                return index;
            }
            table[nums[i] - min] = i;
        }
    }
    free(table);
    return index;
}

 

posted on 2018-02-27 22:50  米兰达莫西  阅读(147)  评论(0编辑  收藏  举报