程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> c語言-求大神幫忙 C語言 LeetCode的 Two Sum問題

c語言-求大神幫忙 C語言 LeetCode的 Two Sum問題

編輯:編程解疑
求大神幫忙 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); }

最佳回答:


 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);
}

如果你的程序沒有別的錯,它和它的調用者應該是這樣的

qq_31933059
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved