本篇內容主要講解“如何編寫代碼實現兩數之和”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“如何編寫代碼實現兩數之和”吧!
給定一個整數數組和一個目標值,找出數組中和為目標值的兩個數。
你可以假設每個輸入只對應一種答案,且同樣的元素不能被重復利用。
示例:
給定 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;
}到此,相信大家對“如何編寫代碼實現兩數之和”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。