Frankjunyu 2016-01-21 17:13 采纳率: 58.8%
浏览 9319
已采纳

求大神帮忙 C语言 LeetCode的 Two Sum问题

求大神帮忙。我run时显示Runtime Error,不知道问题在哪里。。
还有,我也不理解注释中的: * Note: The returned array must be malloced, assume caller calls free(). 这句是什么意思

题目:
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Subscribe to see which companies asked this question

我的代码:
/**

  • Note: The returned array must be malloced, assume caller calls free(). / int twoSum(int* nums, int numsSize, int target) { int i,j; int index1,index2; for(i=0;i<numsSize;i++) { for(j=0;j<numsSize;j++) { if(nums[i]!=0 && nums[j]!=0) { if(nums[i]+nums[j]==target) { if(nums[i]<=nums[j]) { index1=i+1; index2=j+1; } else { index1=j+1; index2=i+1; } } } } } printf("[%d,%d]",index1,index2); }
  • 写回答

2条回答

  • threenewbee 2016-01-21 18:57
    关注
     int* twoSum(int* nums, int numsSize, int target) {
        int i,j;
        int index1,index2;
        for(i=0;i<numsSize;i++)
        {
            for(j=0;j<numsSize;j++)
            {
                if(nums[i]!=0 && nums[j]!=0)
                {
                    if(nums[i]+nums[j]==target)
                    {
                        if(nums[i]<=nums[j])
                        {
                            index1=i+1;
                            index2=j+1;
                        }
                        else
                        {
                            index1=j+1;
                            index2=i+1;
                        }
                    }
                }
            }
        }
        printf("[%d,%d]",index1,index2);
        int * arr = (int *)malloc(sizeof(int) * 2);
        arr[0] = index1;
        arr[1] = index2;
        return arr;
    }
    
    int main()
    {
        int nums[] = {2,7,11,15};
        int *p  = twoSum(nums, 4, 9);
        free(p);
    }
    

    如果你的程序没有别的错,它和它的调用者应该是这样的

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog