leetcode-【简单题】Two Sum

本文详细解析了一道经典算法题“两数之和”的解决方案,通过遍历数组找到两个数,使它们的和等于特定的目标值。文章提供了一个简单但效率较低的O(n^2)算法实现,适用于初学者理解和掌握基本的算法思想。

题目

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.

样例:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

答案:

简单遍历vector就行了,size*size复杂度,本来想先排序,再遍历,但是排序需要记录排序前和排序后索引的对应关系。

代码:

 1 #include <algorithm>
 2 
 3 class Solution {
 4 private:
 5    static bool cmp(const int &a, const int &b)
 6    {
 7        return a < b;
 8    }
 9    
10 public:
11     vector<int> twoSum(vector<int>& nums, int target) {
12        // std::sort(nums.begin(),nums.end(),cmp);
13         
14         int i,j;
15         int size = nums.size();
16         int rest;
17         vector<int> ans;
18         
19         for(i = 0; i < size; ++ i)
20         {
21             rest = target - nums[i];
22             for(j = i + 1;j < size; ++ j)
23             {
24                 if(rest == nums[j])
25                 {
26                     ans.push_back(i);
27                     ans.push_back(j);
28                     return ans;
29                 }
30             }
31         }
32     }
33 };
View Code

 

转载于:https://www.cnblogs.com/Shirlies/p/5211829.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值