Leetcode 1. Two Sum

本文首发于 每日一题:1 - 咸鱼Blog

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

 Input:nums = [2,7,11,15], target = 9
 Output:[0,1]
 Explanation:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

Example 2:

 Input:nums = [3,2,4], target = 6
 Output:[1,2]

Example 3:

 Input:nums = [3,3], target = 6
 Output:[0,1]

Constraints:

  • 2 <= nums.length <= 104

  • -109 <= nums[i] <= 109

  • -109 <= target <= 109

  • Only one valid answer exists.

Solution code

 int* twoSum(int* nums, int numsSize, int target, int* returnSize){
     if (numsSize==0)return NULL;
     for(int i=0;i<numsSize-1;i++){
         if(nums[numsSize-1]+nums[i]==target){
             int *result=(int*)malloc(sizeof(int)*2);
             result[0]=i;
             result[1]=numsSize-1;
             *returnSize=2;
             return result;
         }
     }
     return twoSum(nums,numsSize-1,target,returnSize);
 }

Note:

这种方式复杂度是O(N^2),每次找到最后一个数字,判断前面每个数字与其相加是否符合,如果全部不符合,则标记的数组长度简短,逻辑上删除最后一个元素。

想要得到更优的复杂度,可以采取这样的方式:

  1. table_sort,对其进行大小排序的同时不打乱位置,在排序过程中采取quick_sort可以达到平均复杂度O(NlgN)

  2. 排序后,分别从两头向中间逼近,如果两个和大于目标,则达头的指针内移,小于目标则小头指针内移;在遇到找到目标位置或者两个指针相遇后,离开循环,复杂度O(N);

  3. 因此总的复杂度为O(NlgN).

  4. 但是空间复杂度明显增加

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值