本篇內(nèi)容主要講解“如何編寫代碼實現(xiàn)兩數(shù)之和”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“如何編寫代碼實現(xiàn)兩數(shù)之和”吧!
成都創(chuàng)新互聯(lián)是工信部頒發(fā)資質(zhì)IDC服務(wù)器商,為用戶提供優(yōu)質(zhì)的雅安服務(wù)器托管服務(wù)
給定一個整數(shù)數(shù)組和一個目標值,找出數(shù)組中和為目標值的兩個數(shù)。
你可以假設(shè)每個輸入只對應(yīng)一種答案,且同樣的元素不能被重復(fù)利用。
示例:
給定 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; }
到此,相信大家對“如何編寫代碼實現(xiàn)兩數(shù)之和”有了更深的了解,不妨來實際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學習!
名稱欄目:如何編寫代碼實現(xiàn)兩數(shù)之和
當前地址:http://chinadenli.net/article34/pijcse.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標簽優(yōu)化、響應(yīng)式網(wǎng)站、關(guān)鍵詞優(yōu)化、網(wǎng)站營銷、搜索引擎優(yōu)化、虛擬主機
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)