Leetcode:1. Two Sum

题目:

1.Two Sum

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.

解题思路:一般做法是数组中第一个元素逐次和其之后的元素相加,并逐次检查其和是否等于目标值,若有符合要求的,则返回这两个元素的下标并结束程序,若无符合要求的,则用第二个元素,逐次和其之后的元素相加,并逐次检查其和是否等于目标值,若有符合要求的,则返回这两个元素的下标并结束程序。。。。如此重复,若无符合条件的则返回NULL;而本人的方法是前后同步进行相加并检查,代码如下:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    int* ans=NULL;
    int inv_i, inv_j;
    ans = (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)
            {
                ans[0] = i, ans[1] = j;
                return ans;
            }
            inv_i = numsSize - i - 1;
            inv_j = numsSize - j + i;
            if (nums[inv_i] + nums[inv_j] == target)
            {
                ans[0] = inv_j, ans[1] = inv_i;
                return ans;
            }
        }
    }
    return ans;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值