LeetCode第一题
来源:互联网 发布:怎么查看服务器端口 编辑:程序博客网 时间:2024/06/05 18:29
题意:在一组整数中找到两个数的,使它们的和等于给定的一个整数。
思路:要找到ai+aj=target,只需要枚举ai,对于每一个ai,在(i+1,n)中找到aj=target-ai。
查找如果用顺序查找会超时,可以用二分查找。用二分查找之前要排序,所以要先记下原来的下标。
复杂度:O(nlogn)
代码:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<pair<int,int>> temp;
for(int i=0;i<nums.size();i++)
{
temp.push_back(make_pair(nums[i],i));
}
sort(temp.begin(),temp.end(),cmp);
for(int i=0;i<temp.size();i++)
{
int another=target-temp[i].first;
//查找,使用lower_bound函数更方便
int low=i+1,high=temp.size()-1;
int mid=(low+high)/2;
while(low<=high)
{
mid=(low+high)/2;
if(temp[mid].first==another)
{
vector<int> result;
result.push_back(temp[i].second);
result.push_back(temp[mid].second);
return result;
}
else if(temp[mid].first<another)
{
low=mid+1;
}
else high=mid-1;
}
}
vector<int> a;
return a;
}
static bool cmp(pair<int,int> a,pair<int,int> b)
{
return a.first<b.first;
}
};
- leetcode第一题
- leetcode第一题
- LeetCode OJ 第一题
- Leetcode第一题
- leetcode第一题
- leetcode第一题
- LeetCode第一题
- leetcode第一题
- LeetCode 测试第一题
- LeetCode 第一题
- leetcode第一题twoSum
- LeetCode第一题
- leetcode算法第一题
- LeetCode 1.Two Sum ------------LeetCode 第一题
- leetcode刷题第一题
- leetcode 第一题 two sum
- LeetCode 第一题,Two Sum
- leetcode第一题two sum
- UVa OJ 12627 - Erratic Expansion
- hashtables之哈希桶法
- python常见HTTPError异常
- 记录mysql中的DATE_FORMAT()函数的使用
- 前端开发中的部分兼容性问题
- LeetCode第一题
- <Pro ASP.NET MVC 5> - Note01
- DVB-SI理解入门指南(一)(二)(三)
- 微信公众号开发---微信支付(JS API) JAVA
- JUnit4 执行测试时报initializationError错误
- spring视图国际化locale
- POJ 2566(尺取法+前缀和排序)
- 【Redis】事务和持久化
- viewport属性