1. Two Sum (to be continue~~~~)

Description:

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].
给定一个整形数组,找出两个数的总和等于一个特定的目标,返回这两个数字的索引。

可以假设每个输入都有一个解决方案,并且可能不会使用相同的元素两次。


暴力解法O(n^2)

用双层for循环,,对于数组a中的每一个数据a[i]判断后面是否有某个数a[j],使得a[i]+a[j]=target;


int* twoSum(int* nums, int numsSize, int target) {
    int *a=(int *)malloc(sizeof(int)*2);
    int i,j;
    for(i=0;i<numsSize;i++)
    {
        for(j=i+1;j<numsSize;j++)    //不能用j<=numSize
        {
            if(nums[i]+nums[j]==target)
            {
                a[0]=i;
                a[1]=j;
               return a;
            }
        }
    }
    return NULL;
}

注意 j<numSize 不能有等于,倘若有的话会出现:


        如上,最后两个数据就会出问题



进阶解法:使用Hash表

cpp中的STL容器封装了Hash的实现,使用cpp的话可以减少代码量的同时减少时间复杂度到O(n)

但由于我现在还没有学cpp,Hash表的实现也不熟,过段时间来更新该解法...

...... 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值