LeetCode OJ 第1题 Two Sum 解题报告
来源:互联网 发布:广东梅县东山中学 知乎 编辑:程序博客网 时间:2024/05/17 22:04
试题
试题链接
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
试题大意
给定一组整数,用numbers表示,给定一个整数,用target表示。
请问numbers中的第几个数与第几个数相加等于target。(1起计数)
解题思路
由于数据量不大,可以直接暴力水过。
第一步:从小到大排序,当然同时需要记录原始的下标。
所以先把数据复制到vector <pair<int,int> >
中,pair::first
储存原始下标,pair::second
储存原始数据。然后按照来pair::second
来排序。
第二步,循环枚举。
逐一枚举第一个数number1
,然后第二个数必为target-number1
,找到target-number1
是否存在于numbers
中就行了。直到存在为止。这里查找可以用二分查找,因为前面第一步已经排序排好了。
第三步,输出这两个数的原始下标
源代码
bool compare(const pair<int, int> &a, const pair <int, int> &b){ return a.second < b.second;}class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { int length = nums.size(); vector <pair<int,int> > v; for (int i = 0; i < length; ++i) v.push_back(make_pair<int, int>(i + 1, (int)nums[i])); sort(v.begin(), v.end(), compare); for (vector <pair<int,int> >::iterator itr = v.begin(); itr != v.end(); ++itr) { pair<int,int> diff; diff.second = target - itr->second; vector <pair<int,int> >::iterator itr_tmp = itr; ++itr_tmp; pair<vector <pair<int,int> >::iterator, vector <pair<int,int> >::iterator> p = equal_range(itr_tmp, v.end(), diff, compare); if (p.first != p.second) { vector <int> ret; if (itr->first < p.first->first) { ret.push_back(itr->first); ret.push_back(p.first->first); } else { ret.push_back(p.first->first); ret.push_back(itr->first); } return ret; } } }};
- LeetCode OJ 第1题 Two Sum 解题报告
- LeetCode OJ 第2题 Add Two Numbers 解题报告
- Leetcode (1) Two Sum 解题报告
- LeetCode(1) Two Sum解题报告
- LeetCode 解题报告 Two Sum
- LeetCode-Two Sum-解题报告
- [LeetCode] Two Sum 解题报告
- 【LeetCode】Two Sum 解题报告
- LeetCode OJ 第1题 (Two Sum )
- [Leetcode]之一《two sum》解题报告
- [leetcode] 1. Two Sum 解题报告
- LeetCode 1. Two Sum 解题报告
- LeetCode 1.Two Sum 解题报告
- 【LeetCode】1. Two Sum 解题报告
- LeetCode 167.Two Sum II 解题报告
- LeetCode 1.Two Sum 解题报告
- [Leetcode] 1. Two Sum 解题报告
- leetcode解题报告1. Two Sum
- AngularJS学习(一)
- python 中文处理----全角半角以及查看编码值
- [python]标准库json格式化工具
- throw的概述以及和throws的区别
- B - Gary's Calculator
- LeetCode OJ 第1题 Two Sum 解题报告
- String、StringBuffer、StringBuilder之间的区别-整理中
- 好短的一个学期
- 【Effective Objective-C 2.0读书笔记】第五章:内存管理
- Java 微信公众号平台接入 视频
- 在ActionBar中,即便设置showAsAction="always",items仍然在overflow中显示的问题...
- object-c调用swift -swift file not found
- LeetCode223:Rectangle Area
- Oracle数据库之PL/SQL程序设计简介