Two Sum

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

时间复杂度为O(n)的一种解法为:

 1 int* twoSum(int* nums, int numsSize, int target) 
 2 {
 3     int index[100001] = {0}, *index_plus_one = index + 50000;//索引从index数组的第50000个元素开始,避免出现负数索引报错;
 4     for (int i = 0; i < numsSize; i++) 
 5     {
 6         int rest = target - nums[i];
 7         if (index_plus_one[rest]) 
 8         {
 9             //如果rest这个索引已经计算过了,那么就可以得出答案
10             int *ans = malloc(sizeof(int) * 2);
11             ans[0] = i;
12             ans[1] = index_plus_one[rest] - 1;
13             return ans;
14         }
15         else
16             index_plus_one[nums[i]] = i + 1;//如果rest这个索引没有计算过,那么就将 index_plus_one[nums[i]] 标记为大于0;
17     }
18     return NULL;
19 }

 

转载于:https://www.cnblogs.com/wanfeng-42/p/8575443.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值