leetCode-day1

#1.两数之和

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
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.

示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
// 结果为动态数组
int *pArray = malloc(sizeof(int) * 2);
int j = 0;
int i = 0;
for (i = 0; i < numsSize; i++)
{
for (j = i + 1; j < numsSize; j++)
{
if((nums[i] + nums[j]) == target)
{
pArray[0] = i;
pArray[1] = j;
break;
}
}
}

return pArray;
}

tips:if语句不加大括号的话,只是判断离if最近的语句是否执行。

-------------本文结束 · 感谢您的阅读-------------

本文标题:leetCode-day1

文章作者:Pinkpear

发布时间:2018年06月26日 - 16:06

最后更新:2018年06月26日 - 17:06

原始链接:http://pinkpear.github.io/2018/06/26/leetCode-day1/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。