1. Two Sum
来源:互联网 发布:移动光纤网络机房在哪 编辑:程序博客网 时间:2024/06/07 02:23
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
解法1:
用unordered_map存储vector中每个元素对应的index,遍历的时候查找是否之前已经储存过元素x,满足nums[i] + x == target。
若存在,则输出结果;若不存在,则将这个元素及其index加入unordered_map。
时间复杂度:O(n)
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> index; for (int i = 0; i < nums.size(); i++) { if (index.find(target - nums[i]) != index.end()) { return vector<int>({index[target - nums[i]], i}); } index[nums[i]] = i; } return vector<int>(2, -1); }};
解法2:
先将vector中元素升序排序,再用两个游标left和right分别从vector两端遍历。
若element[left] + element[right] == target,则返回它们的index;
若element[left] + element[right] < target,则left游标向右移动;反之right游标向左移动。
由于最后需要返回元素的原始index,所以首先需要建立一个数据结构Elem记录元素对应的index和它的值。
时间复杂度:O(n log n)
class Solution {public: struct Elem { int index; int val; Elem(int i, int v) : index(i), val(v) {} }; static bool Comp(Elem a, Elem b) { return a.val < b.val; } vector<int> twoSum(vector<int>& nums, int target) { vector<Elem> elements; for (int i = 0; i < nums.size(); i++) { elements.push_back(Elem(i, nums[i])); } sort(elements.begin(), elements.end(), Comp); int left = 0; int right = nums.size() - 1; vector<int> result(2, -1); while (left < right) { int sum = elements[left].val + elements[right].val; if (sum == target) { result = vector<int>({elements[left].index, elements[right].index}); sort(result.begin(), result.end()); return result; } else if (sum < target) { left++; } else { right--; } } return result; }};
0 0
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- 常用Linux操作
- 15My3.0版本聊天系统(mybatis集成)
- php的Generator生成器及yield
- Leetcode 166. Fraction to Recurring Decimal
- CSS基础入门3
- 1. Two Sum
- Managed Server Independence
- centos升级openssh的两种方式
- c语言中数组名代表数组首地址,它的值在运行期间可以改变吗?
- 关于jQuery的$.getJSON乱码问题
- Easyui笔记2:实现datagrid多行删除
- RXjava的简单介绍 请求网络的Demo menglong0329
- HH问题的解答
- 什么是Cluster集群