LeetCode 1. Two Sum(c语言实现)
来源:互联网 发布:python图片验证码识别 编辑:程序博客网 时间:2024/05/16 12:50
问题描述:
给定一个数组,找出两个元素,其相加等于一个给定的目标值,返回这两个元素的索引值。
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、找出数组的两个索引值;
2、返回两个索引值,可以采用结构体指针、数组形式,本例采用前一种。
/** * Note: The returned array must be malloced, assume caller calls free(). */int* twoSum(int* nums, int numsSize, int target) { int i,j; struct returns{ int a; int b; }A,*p; p=&A;//不能省略A的定义 for(i=0;i<=numsSize;i++){ for(j=i+1;j<=numsSize;j++){ if(nums[i]+nums[j]==target){ // A=malloc(sizeof(struct returns)); // A=malloc(sizeof(p)); // A=malloc(sizeof(A)); p=(struct returns*)malloc(sizeof(struct returns));//只能赋值给指针类型,而不是struct returns类型 p->a=i; p->b=j; break; } } } return p;}
其实上面的代码是有问题的,两个for循环里面存在数组越界,所以提交的时候是过不了的。正确的答案如下:
/** * Note: The returned array must be malloced, assume caller calls free(). */int* twoSum(int* nums, int numsSize, int target) { int i,j; struct returns{ int a; int b; }A,*p; p=&A;//不能省略A的定义 for(i=0;i<numsSize;i++){//注意看清题目,不要出现数组越界 for(j=i+1;j<numsSize;j++){ if(nums[i]+nums[j]==target){ p=(struct returns*)malloc(sizeof(struct returns));//只能赋值给指针类型,而不是struct returns类型 p->a=i; p->b=j; break; } } } return p;}
不足之处是这个函数的时间复杂度达到了O(N2),不是最理想的。
转载请注明出处。
阅读全文