LeetCode(easy)-1、Two Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/f823154/article/details/82872949

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].
题目:
给定一个整型数组,返回两个数字的下标,使它们相加满足一个整数。
假设每次输入只有一个元素,且不会使用两次相同的元素。
例:
nums = [2,7,11,15],target = 9,
nums [0] + nums [1] = 2 + 7 = 9,
返回[0,1]。
解法一:

/*
*  C语言
*/
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    int *index = (int*)malloc(2*sizeof(int));
    for(int i = 0;i<numsSize;i++)
    {
        for(int j = i+1;j<numsSize;j++)
        {
            if(nums[i] + nums[j] == target)
            {
                index[0] = i;
                index[1] = j;
                break;
            }
        }
    }
    return index;
}	

LeetCode运行时间:72ms

猜你喜欢

转载自blog.csdn.net/f823154/article/details/82872949
今日推荐