[leetcode]1.Two Sum

2017-12-22  本文已影响0人  cherrycoca

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, 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].

思路:进行两次for循环实现数组中任意两数相加求和,并与目标值进行判断,输出对应的元素位置。

问题:一开始,在本地编译器编译可以通过(用给出的个例时),但submit时报错提示“load of null pointer of type ‘const int’ ”,整数类型空指针的加载。之后修改了line12中n的值,一开始错想成有Cn(n-1)种结果,即给n赋了该值,但n是for循环的边界,应该是数组中的个数,修改后即可accepted。

代码

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    
    int *p; 
    p=(int *)malloc(sizeof(int)*2);    
     if(p!=NULL)  
    {   
         int i;
    int j;  
    int n=numsSize;

    if(n<0 || nums==NULL)
        return NULL;
    for(int i=1;i<n;i++)  
    {  
        for(int j=0;j<i;j++){
            if((nums[i]+nums[j])==target){
                p[0]=j;
                p[1]=i;
                return p;
            }
        }
    } 
         
    }    
   
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读