码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode(Two Sum)

时间:2019-01-12 00:21:24      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:str   one   amp   ==   example   malloc   题目   code   may   

一、题目要求

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

二、解法

C语言

 1 /**
 2  * Note: The returned array must be malloced, assume caller calls free().
 3  */
 4 int* twoSum(int* nums, int numsSize, int target) {
 5     int* result = (int *)malloc(2 * sizeof(int));
 6     for(int i = 0; i < numsSize - 1; i++) {
 7         int a = nums[i];
 8         for(int j = i + 1; j < numsSize; j++ ) {
 9             if(nums[i] + nums[j] == target) {
10                 result[0] = i;
11                 result[1] = j;
12                 return result;
13             }
14         }
15     }
16     return result;
17 }

运行结果:

技术分享图片

 

LeetCode(Two Sum)

标签:str   one   amp   ==   example   malloc   题目   code   may   

原文地址:https://www.cnblogs.com/zou107/p/10258190.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!