Leetcode刷题笔记1:Two Sum(C语言)

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) 
{
    int i,j,flag=0;
    int *s = (int*)malloc(2*sizeof(int));
    for(i=0;i<numsSize;i++)
    {
        for(j=i+1;j<numsSize;j++)
        {
            if(i!=j)
            {
                if(nums[i]+nums[j]!=target)continue;
                else{ s[0]=i;s[1]=j;flag=1;}
            }
        }
        if(flag==1)break;
    }
    return s;
}

得到以下结果:

感觉太慢了,又改了改:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    static int s[2] = {0};
    for(int i = 0; i < numsSize - 1;i++)
    {
        for(int j = i+1;j < numsSize;j++)
        {
            if(target == (nums[i]+nums[j]))
            {
                a[0] = i;a[1] = j; return s;
            }
        }
    }
    return 0;
}
时间上有好一点点:

猜你喜欢

转载自blog.csdn.net/weixin_41036461/article/details/88869845