LeeCode编程训练日记一:Two Sum
来源:互联网 发布:警察查封淘宝假章 编辑:程序博客网 时间:2024/05/21 15:44
通过Leecode训练编程,每天只做一个题目,重在训练编程思想
Practice Day 1: 2017/06/25
参考:http://blog.csdn.net/murdock_c/article/details/49851547
test 1:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
解答:
1、暴力计算(不推荐,时间复杂度太高)
#include<iostream>using namespace std;int main() { int arr[4] = {2,7,11,15}
int target;
int a,b; cin >> target;
int length = sizeof(arr)/sizeof(arr[0]);
for(int i = 0; i < length; i++){
for(int j = i+1; j< length; j++) {
if(arr[i] + arr[j] == target)
{
a = i;
b = j;
break;
}
}
}
cout << arr[a] << " & " << arr[b] << endl;
return 0; }
2、c++ map的方法来做,时间复杂度因为map查找速度快的原因而大大下降
#include<iostream>#include<vector>#include<map>using namespace std;class Solution {public: vector<int> twosome(vector<int> numbers, int target) { int i, sum; vector<int> results;
map<int, int> hmap;
for(int i=0; i < numbers.size(); i++)
{
if(!hmap(numbers[i])){
map.insert(pair<int,int>(numbers[i], i));
}
if(map.count(target - numbers[i]))
{
int n = hmap[target - numbers[i]];
if(n < i)
{
results.push_back(n);
results.push_back(i);
return results;
}
}
}
return results;}};
int main() {
vector<int> numbers = {2,7,11,15};
vector<int> res;
int target;
cin >> target;
Solution solution;
res = solution.twosum(numbers, target);
cout << " 返回的下标的索引分别为:";for(int i = 0; i < 2; i++){cout << res[i] << ","}return 0;}
if(!hmap(numbers[i])){map.insert(pair<int,int>(numbers[i], i));这句意思就是如果numbers[i]在map中没有出现过,就将(numbers[i],i)插入到map中,其中numbers[i]相当于key,i相当于value。因为map中的查找是很快的,所以时间复杂度很低。
另外,map要求其中的key值不允许重复,即一个key只对应一个value。
阅读全文
0 0
- LeeCode编程训练日记一:Two Sum
- LeeCode--Two Sum
- LeeCode-Two Sum
- leecode(1)Two Sum
- leecode algo1: Two Sum (Java)
- Leecode 刷题1 Two Sum
- leecode 第一题 TWO SUM
- [leecode 170] Two Sum III - Data structure design
- leecode 167. Two Sum II - Input array is sorted
- 一、Two Sum
- 【Two Sum】 --MyLeetCode(一)
- leetcode编程笔记(一)——two sum
- Leetcode刷题日记 -- Two Sum
- leetcode算法训练#1 Two Sum
- LeetCode(一)Two Sum
- Algorithms(一)Two Sum
- 每日一题:Two Sum
- LeeCode---Add Two Numbers
- spring xml 文件的一些写法,包括map ,set ,list 等
- 计算机网络应用层(一)应用协议原理
- vmware net转发映射ssh端口
- 二叉搜索树—增删查
- rhel6.4部署gateone
- LeeCode编程训练日记一:Two Sum
- 看雪ctf记录第一题
- Linux误删文件教训,吃一堑长一智
- rhel6.4部署tomcat
- 运算符注意的问题
- 开源框架源码分析:网速监听—facebook/network-connection-class
- Linux-rhel6.4部署nginx
- Linux-rhel6.4 编译安装PHP,Nginx与php连接
- Linux 制作本地yum源