LeetCode | 1.Two Sum

来源:互联网 发布:法律大数据 编辑:程序博客网 时间:2024/06/01 19:07

LeetCode|1.Two Sum

Give an array of integers,find two numbers such that they add up to a specific target number.

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

Example:

Input: numbers={2, 7, 11, 15}, target=9

output: index1=1, index2=2

编程思路

题目的要求是给定一组数,从中找到和为一个给定值的两个数,并返回它们的下标。即找到a和b满足a+b=target。

思路一:

遍历数组中的某一个数,在遍历其之后的所有数,计算并找到满足要求的两个数,结束遍历返回下标。时间复杂路为O(N(N -1)),即O(N^2)。空间复杂度为O(1)。

代码: (C)

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

思路二:






0 0
原创粉丝点击