1. Two Sum

来源:互联网 发布:sal绘画软件 sai 编辑:程序博客网 时间:2024/05/22 21:24

问题描述:

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

解题思路:

先开辟一个2个int空间的数组a用来存放满足要求的整数的下标。

使用双层for循环遍历nums数组,将两两之和与target比较,如果相等则将两个数的下标存放进数组a并返回。

C语言解题代码

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

体会:

本题解题方法简单,难点在与c语言无法直接返回数组, 所以做题时被卡在了返回数组的问题上。解决方法是采用指针来传递。

声明了一个指针之后还需要为其开辟一个内存空间。

算是复习了一下数组和指针两方面的知识。



0 0
原创粉丝点击