LeetCode 1

Two Sum

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.

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

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

 

注意:此题一定要malloc返回数组!

 

 1 /*************************************************************************
 2     > File Name: LeetCode001.c
 3     > Author: Juntaran 
 4     > Mail: Jacinthmail@gmail.com
 5     > Created Time: 2016年04月25日 星期日 00时37分25秒
 6  ************************************************************************/
 7  
 8 /*************************************************************************
 9 
10     Two Sum
11     
12     Given an array of integers, return indices of the two numbers such that they add up to a specific target.
13 
14     You may assume that each input would have exactly one solution.
15 
16     Example:
17     Given nums = [2, 7, 11, 15], target = 9,
18 
19     Because nums[0] + nums[1] = 2 + 7 = 9,
20     return [0, 1].
21 
22  ************************************************************************/
23 
24 
25 #include <stdio.h>
26 #include <malloc.h> 
27 
28 int* twoSum(int* nums, int numsSize, int target) {
29     
30     int i = 0;
31     int j = 0;
32  //   int result[2];
33     int *result = (int*)malloc(sizeof(int));
34     
35     
36     for( i=0; i<numsSize; i++){
37         for( j=i+1; j<numsSize; j++ ){
38             if( ( target - nums[i] ) == nums[j] ){
39                 result[0] = i;
40                 result[1] = j;
41                 printf("[%d,%d]\n",result[0],result[1]);
42                 return result;
43             }
44         }
45     }
46     printf("Not Fount!\n");
47     return 0;
48 }
49 
50 int main(){
51     
52     int nums[] = {0,4,3,0};
53     int numsSize = 4;
54     int target = 0;
55     
56     twoSum( nums, numsSize, target);
57     
58     return 0;
59 }

 

posted @ 2016-04-25 00:49  Juntaran  阅读(149)  评论(0编辑  收藏  举报