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),不是最理想的。
转载请注明出处。

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 姓邓的名字 姓邓的男孩名字大全 姓邓男孩名字 邓姓宝宝取名 姓邓的辈份顺序 邓姓女孩取名有诗意的 邓姓男孩取名100分 邓姓起名 姓邓的男孩霸气名字 姓邓男孩取名字 邓姓取名女孩 姓邓女孩洋气的名字 邓姓宝宝起名 2018独特好听的男孩名字姓邓 2018年100分女孩名字大全集邓姓 2018男孩帅气有涵养的名字姓邓 那姓 韩姓与那姓不能通婚 姓郑名字 郑姓取名 姓郑男孩名字 郑姓起源 郑姓男孩取名 姓郑的明星 郑姓女孩起名 姓郑的男孩名字 郑姓名字 郑姓孩子取名 郑姓起名 宝宝名字姓郑 郑姓男孩取名100分 姓郑的女孩名字 姓郑的名字大全 郑姓女孩子名字大全 郗作为姓念什么 姓曾 郝姓起名 郝姓起源 郝姓女孩洋气名字 郝姓女孩名字大全 郝姓男孩名字