Two Sum-----LeetCode
来源:互联网 发布:君君的淘宝店 编辑:程序博客网 时间:2024/06/05 20:39
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2
类似于july 100题
第 14 题:
题目:输入一个已经按升序排序过的数组和一个数字,在数组中查找两个数,使得它们的和正好是输入的那个数字。要求时间复杂度是 O(n)。如果有多对数字的和等于输入的数字,输出任意一对即可。例如输入数组 1、2、4、7、11、15 和数字 15。由于 4+11=15,因此输出 4 和 11。
#include <stdio.h>//#include <string.h>#include <stdlib.h>void twosum(int *array, int sum){int *tmp;int i,j;tmp = (int *) malloc(sizeof(array) * sizeof(int));for(i=0; i<sizeof(array); i++){tmp[i] = sum - array[i];}for(i=0; i<sizeof(array); i++){printf("%d\t",array[i]);}i = 0;j = sizeof(array) -1 ;while(array[i] != tmp[j]){if(array[i] < tmp[j])++i;else--j;}printf("%d + %d = %d\n",array[i],array[j],sum);}void main(){int array[] = {1,2,4,7,11,15};twosum(array,9);}
(1)sizeof
方法:sizeof(数组名)/ sizeof(数组类型名)
说明:数组占用字节除以数组类型所占字节,结果为数组元素个数
(2)strlen
说明:strlen,求字符串有效长度
方法:strlen(字符数组名) //结果为字符数组有效字符长度,不包括末尾的' /0'
注意:
当数组作为函数参数传递时,数组名代表的是数组的首址,而非数组内容,故无法使用sizeof和strlen;
所以,在传址时,应提供2个参数:1个是数组名,代表数组首地址;1个是数组元素个数,以便确定传递的次数。
当数组作为函数参数传递时,数组名代表的是数组的首址,而非数组内容,故无法使用sizeof和strlen;
所以,在传址时,应提供2个参数:1个是数组名,代表数组首地址;1个是数组元素个数,以便确定传递的次数。
0 0
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- Java编码规范
- STM32F103VCT6+W5500 Telnet服务实现,可远程登陆并实现控制
- 2014ACM集训13级PK赛4-K-Nice
- Struts2 自动登录的拦截器
- 和matlab链接是显示Can't load IA 64-bit .dll on a AMD 64-bit
- Two Sum-----LeetCode
- Visual Studio 2012旗舰版序列号:
- 1024. Palindromic Number
- Cocos2d-x 3.0 开发(十七)使用Cocos2d-x 3.0rc,一条命令打包Android
- win8.1 64位系统下正确安装串口转usb驱动
- Rotate Image
- 日期与时间处理
- .net开发框架
- 《Pyhon简明教程》学习摘要