1.twosum

最近发现自己代码能力很菜,为了明年秋招能找到合适的工作,决定从现在开始刷LeetCode,开个博客记录一下刷题遇到的问题,也方便后面查看回顾。

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

题意很简单,数组中两个值相加等于指定的值,返回这两个值的下标:
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target)
{   int *a = (int*)malloc(2*sizeof(int));
    for (int i=0;i<numsSize;i++)
   {      for (int j=i+1;j<numsSize;j++)
           { if (nums[i]+nums[j]==target)
              { a[0]=i;
                a[1]=j;
             }
            else
                continue;
            }
   }
return a;
}

由于自己对C语言相对来说熟悉一点,还是倾向于用C语言,python学的不上不下的,很尴尬,语言这种东西很奇妙,你第一次学的什么语言,后面遇到问题就总是习惯用这种语言思考,即使可以用别的语言写出来,好像也是在“母语”基础上翻译一样。OK,后面再加强python的训练吧。

这里遇到的问题是开始是定义一个数组a来存放下标,我开始写的是 int a[2]; 报错信息:

load of null pointer of type 'const int'

后来改成 int *a = (int*)malloc(2*sizeof(int)); 通过了运行。

后来查看资料才知道,这是初学者很容易犯的错误,前面加上static就行了,static int a[2];顺利通过。

OK,用两个for循环通过了测试,但是这是最暴力的方法,时间复杂度为O(n^2),基本上是最差的解法了,下面就要优化代码,降低时间复杂度。

 

 

 

参考链接:

https://www.cnblogs.com/Elaine-DWL/p/8097944.html

https://www.jianshu.com/p/7d8719358000

https://blog.youkuaiyun.com/yake827/article/details/50995807

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九城风雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值