LeetCode | 1.Two Sum
2016-05-21 16:06
344 查看
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=9output: 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; }
思路二:
相关文章推荐
- getCacheDir()、getFilesDir()、getExternalFilesDir()、getExternalCacheDir()的作用
- 1.border-image
- UWSGI安装与使用
- LintCode : Jump Game II
- 笔记本_thinkpad_e40
- Coursera机器学习 week3 逻辑回归 编程作业代码
- Volley(1)—发送get和post请求
- python文本分类准备工作-扩展库的安装
- 字符串匹配的BM算法讲解(不含代码)
- hash
- 小球和箱子
- AngularJS 的常用特性(一)
- 笔记本_hp
- Java实现文件上传的方法
- Mybatis中运用小技巧(二) like的使用
- unity屏幕空间坐标shader
- 欢迎使用CSDN-markdown编辑器备份
- Git 常用命令
- linux下创建和删除软、硬链接
- margin重叠现象探讨研究