[C语言][LeetCode][1]Two Sum

来源:互联网 发布:网络劫持是什么意思 编辑:程序博客网 时间:2024/05/18 00:20

题目

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].

标签

Array

难度

简单

分析

题目意思是给定一个整形数组和一个target,查找数组里两数之和为target的下标,并返回。
实现思路是两次循环遍历求解。

C代码实现

int* twoSum(int* nums, int numsSize, int target){    int i=0, j=0;    int * ret = (int *)malloc(2 * sizeof(int));    memset(ret, 0, (2 * sizeof(int)));    for(i=0; i<numsSize; i++)    {        for(j=i+1; j<numsSize; j++)        {            if( (nums[i]+nums[j]) == target)            {                ret[0] = i;                ret[1] = j;                return ret;            }        }    }    return NULL;}
0 0
原创粉丝点击