算法-1-twoSum

题目:

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]

 

“runtime error: load of null pointer of type 'const int'”

返回值为数组的指针,指针指向数组内的局部变量,在return退出时,变量存储空间被销毁,则无法访问;

解决办法:讲变量用static关键字修饰(改关键字声明的变量在程序退出时候仍然存在)

CSDN上其他解决办法:

1.返回的指针使用malloc分配空间;

2.使用全局变量;

 

 

最普通(慢)的算法:

 1 int* twoSum(int* nums, int numsSize, int target) {
 2     //numSize=sizeOf(nums);
 3     static int answer[2];
 4     for(int i=0;i<numsSize-1;i++)
 5     {
 6         for(int j=1;j<numsSize;j++)
 7         {
 8             if(nums[i]+nums[j]==target)
 9             {
10                 answer[0]=i;
11                 answer[1]=j;
12             }
13         }
14     }
15     return answer;
16 }

 给定的例子nums = [2, 7, 11, 15], target = 9是对的,但是submit的时候出现了问题:

此时例子用的(大概)是[0,5,5,11,2],代码出的结果为[2,2],在nums的相同位置上做了重复相加;

将j改成从i的后一个位置开始:

int* twoSum(int* nums, int numsSize, int target) {
    //numSize=sizeOf(nums);
    static int answer[2];
    for(int i=0;i<numsSize-1;i++)
    {
        for(int j=i+1;j<numsSize;j++)
        {
            if(nums[i]+nums[j]==target)
            {
                answer[0]=i;
                answer[1]=j;
            }
        }
    }
    return answer;
}

得出正确结果;

posted @ 2019-03-24 16:25  游歌  阅读(191)  评论(0编辑  收藏  举报