【LeetCode】Two Sum
2015-05-18 17:09
344 查看
题目描述
问题分析
代码
总结
个人声明
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
直接暴力搜索,此时时间复杂度是o(n^2),显然这种方法并不可行
采用hash,存储每一个数值的对应下表,这个复杂度O(n)
对这个数组进行排序,然后进行查找,复杂度是O(nlogn),但是这个题要输出的是下表,并不合适
个人说明
本人对编程有很大兴趣,希望跟大家一起交流
欢迎访问个人论坛:www.dabenmo.com
如有任何问题请邮件:jianxiawzx@126.com
问题分析
代码
总结
个人声明
题目描述
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
问题分析
这道题初一看,应该会有三种解决方案:直接暴力搜索,此时时间复杂度是o(n^2),显然这种方法并不可行
采用hash,存储每一个数值的对应下表,这个复杂度O(n)
对这个数组进行排序,然后进行查找,复杂度是O(nlogn),但是这个题要输出的是下表,并不合适
代码
struct Node { int val; int index; Node(){} Node(int v, int idx):val(v), index(idx){} }; bool compare(const Node &lhs, const Node &rhs) { return lhs.val < rhs.val; } class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<Node> a; for(int i = 0; i < numbers.size(); i++) a.push_back(Node(numbers[i], i + 1)); sort(a.begin(), a.end(), compare); int i = 0; int j = numbers.size() - 1; while(i < j) { int sum = a[i].val + a[j].val; if (sum == target) { vector<int> ret; int minIndex = min(a[i].index, a[j].index); int maxIndex = max(a[i].index, a[j].index); ret.push_back(minIndex); ret.push_back(maxIndex); return ret; } else if (sum < target) i++; else j--; } } };
总结
这个题并不是很难,找到思路还是很简单的个人声明
本文章均为原创,转载请说明出处,谢谢个人说明
本人对编程有很大兴趣,希望跟大家一起交流
欢迎访问个人论坛:www.dabenmo.com
如有任何问题请邮件:jianxiawzx@126.com
相关文章推荐
- leetcode:1. Two Sum
- [LeetCode]Two Sum
- leetcode 1:two sum
- LeetCode---1. Two Sum
- LeetCode | 1. Two Sum 简单循环技巧题
- 刷题的日常[Leetcode]——1)Two Sum
- leetcode-- two sum
- [LeetCode] Two Sum
- leetcode - 1.Two Sum
- [leetcode-1] Two sum
- [LeetCode] Two Sum
- LeetCode1 Two Sum
- LeetCode1_Two Sum
- LeetCode-two sum:python解答数组问题
- leetcode 1. Two Sum
- 【LeetCode-1】Two Sum
- 【LeetCode】1:Two Sum
- leetcode--1. Two Sum
- 【闲来刷 leetcode】 Two Sum | leetcode OJ
- leetcode_1 Two Sum,Longest Common Prefix