本篇内容主要讲解“如何编写代码实现两数之和”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何编写代码实现两数之和”吧!
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15] , target = 9 。
因为 nums[0] + nums[1] = 2 + 7 = 9 ,
所以返回 [0, 1]
1. Swift 语言
2. JavaScript 语言
3. Python 语言
4. Java 语言
5. C++ 语言
6. C 语言
#include <stdio.h>
#include <stdlib.h>
struct object {
int val;
int index;
};
static int compare(const void *a, const void *b)
{
return ((struct object *) a)->val - ((struct object *) b)->val;
}
static int * twosum(int *nums, int numsSize, int target)
{
int i, j;
struct object *objs = malloc(numsSize * sizeof(*objs));
for (i = 0; i < numsSize; i++) {
objs[i].val = nums[i];
objs[i].index = i;
}
qsort(objs, numsSize, sizeof(*objs), compare);
int count = 0;
int *results = malloc(2 * sizeof(int));
i = 0;
j = numsSize - 1;
while (i < j) {
int diff = target - objs[i].val;
if (diff > objs[j].val) {
while (++i < j && objs[i].val == objs[i - 1].val) {}
} else if (diff < objs[j].val) {
while (--j > i && objs[j].val == objs[j + 1].val) {}
} else {
results[0] = objs[i].index;
results[1] = objs[j].index;
return results;
}
}
return NULL;
}
int main(void)
{
//int nums[] = {-1, -2, -3, -4, -5};
//int target = -8;
//int nums[] = {0,4,3,0};
//int target = 0;
int nums[] = { 3, 2, 3 };
int count = sizeof(nums) / sizeof(*nums);
int target = 6;
int *indexes = twosum(nums, count, target);
if (indexes != NULL) {
printf("%d %d
", indexes[0], indexes[1]);
} else {
printf("Not found
");
}
return 0;
}
到此,相信大家对“如何编写代码实现两数之和”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/3375733/blog/5044610