LeetCode题目1
来源:互联网 发布:2014年十大网络流行语 编辑:程序博客网 时间:2024/06/03 12:39
原题:
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, and you may not use the same element twice.
给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。
这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。请注意一点,你返回的结果(包括index1和index2)都不是基于0开始的。假设每一个输入肯定只有一个结果。
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { }};使用两层循环可以完成,时间复杂度为o(n^2),空间复杂度为o(1),但是当输入的数组很大的时候,耗费的时间就会很长,所以需要改进代码。
此时考虑能够搜索的数据结构,考虑使用map,时间复杂度为O(n)。
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> result; map<int, int> m; if (numbers.size() < 2) return result; for (int i = 0; i < numbers.size(); i++) m[numbers[i]] = i; map<int, int>::iterator it; for (int i = 0; i < numbers.size(); i++) { if ((it = m.find(target - numbers[i])) != m.end()) { if (i == it->second) continue; result.push_back(i+1); result.push_back(it->second+1); return result; } } return result; }};
0 0
- LeetCode题目1~3
- leetcode题目总结<1>
- LeetCode题目1
- leetcode题目 1
- leetcode题目
- LeetCode 题目
- < 题目 > LeetCode
- 13.leetcode题目1: Two Sum
- 每天一道leetcode题目_(1)
- leetcode题目解答报告(1)
- leetcode上数据库的题目(1)
- LeetCode题目 Insert Interval
- 【转载】【leetcode】题目分布
- Leetcode 题目分类
- leetcode题目解答---- SortList
- leetcode题目:LRU Cache
- leetcode题目:Reorder List
- leetcode题目:Candy
- Node.js学习笔记(一)基础介绍
- OpenCV模块库简单介绍
- 强制IE浏览器或WebBrowser控件使用指定版本显示网页
- pureftp部署和优化-1
- SourceInsight安装
- LeetCode题目1
- 并查集 数据结构
- UVA 116 Unidirectional TSP(dp)
- 多线程通信
- 如何从PLsql导出数据
- 存储器类型总结
- 在STL泛型算法中的排序函数sort内部使用的是哪种排序算法呢?
- C++Primer第五版 第十章习题答案(31~40)
- u盘插入电脑后识别缓慢该怎么解决