Two Sum-----LeetCode

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个是数组元素个数,以便确定传递的次数。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值