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



0 0
原创粉丝点击