LeetCode | 1. Two Sum 简单循环技巧题

本文介绍了一种高效求解数组中两数之和问题的方法。通过对数组进行排序,并使用双指针技巧来查找目标值,避免了暴力解法可能带来的效率问题。此外,讨论了如何在保持原有数组顺序的情况下,通过额外的数据结构来记录元素位置,从而快速返回原始索引。

Givenan array of integers, return indices of the two numbers such that they add up to a specifictarget.

Youmay assume that each input would have exactly onesolution, 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].

给你一个数组,问你是否有一个数等于数组中两个数的和,这题假如暴力解决的话,可能会超时,这里我没有暴力解决,我先把数组排序,然后设置start=0,end=nums.size()-1,当nums[start]+nums[end]<target的时候,start++,当nums[start]+nums[end]>target,end--,最后当nums[start]+nums[end]==target的时候start,end就是 最后的结果,

而这里当nums无序,的时候,当要求你输出nums中的索引的时候,有两种解决方案,其一是最后在遍历一次原来的nums,找到start和end在原数组中的索引,方法二是实用vector<pair<int,int>>num2第一个int表示nums2当前值在nums中对应的位置,第二个int表示当前位置的值,然后使用

boolcmp(pair<int,int> a,pair<int,int> b)

{

Returna.secont<b.second;

}

这样的最后一步的遍历nums也可以省去,直接返回nums2[start].first,和nums2[end].second就好了

class Solution {

public:

vector<int>twoSum(vector<int>& nums, int target) {

      vector<int> nums2(nums.begin(),nums.end());

      sort(nums.begin(), nums.end());

      int start = 0; int end = nums.size() - 1;int tmp;

      while (start != end)

      {

            tmp = nums[start] + nums[end];

            if (tmp > target) end--;

            else

                  if (tmp < target) start++;

                  else

                  {

                       break;

                  }

      }

      vector<int> result;

      for (int i = 0; i < nums2.size(); i++)

            if (nums2[i] == nums[start])  result.push_back(i);

            else if (nums2[i] == nums[end])result.push_back(i);

           

      return result;

}

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值