Two sum 两数之和
来源:互联网 发布:linux查看oracle版本 编辑:程序博客网 时间:2024/06/06 18:44
给定一个数组和一个特定的数,使得数组中的两个数等于这个特定的数。找出这两个数的下标。
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target){ vector<int> res; if(numbers==null||numbers.length<2) return res; //copy original list and sort vector<int> res copylist ; copylist.assign(numbers.begin(),numbers.end()); copylist.sort(copylist.begin(),copylist.end()); int low = 0; int high = copylist.size()-1; while(low<high){ if(copylist[low]+copylist[high]<target) low++; else if(copylist[low]+copylist[high]>target) high--; else{ res[0]=copylist[low]; res[1]=copylist[high]; break; } } //find index from original list int index1 = -1, index2 = -1; for(int i = 0; i < numbers.size(); i++){ if(numbers[i] == res[0]&&index1==-1) index1 = i+1; else if(numbers[i] == res[1]&&index2==-1) index2 = i+1; } res[0] = index1; res[1] = index2; res.sort(res.begin(),res.end()); return res; }
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { int i, sum; vector<int> results; map<int, int> hmap; for(i=0; i<numbers.size(); i++){ if(!hmap.count(numbers[i])){ hmap.insert(pair<int, int>(numbers[i], i)); } if(hmap.count(target-numbers[i])){ int n=hmap[target-numbers[i]]; if(n<i){ results.push_back(n+1); results.push_back(i+1); //cout<<n+1<<", "<<i+1<<endl; return results; } } } return results; }};
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { map<int, int> mapping; vector<int> res; for (int i = 0; i < numbers.size(); ++i) { mapping[numbers[i]] = i; } for (int i = 0; i < numbers.size(); i++) { int searched = target - numbers[i]; if (mapping.find(searched) != mapping.end() && i != mapping[searched]) { res.push_back(i + 1); res.push_back(mapping[searched] + 1); break; } } return res; }};
阅读全文
0 0
- Two Sum--两数之和
- Two sum 两数之和
- LeetCode Two Sum 两数之和
- leetcode 1 Two Sum 两数之和
- *[Lintcode]Two Sum 两数之和
- Two Sum(两数之和)
- lintcode 两数之和(Two Sum )(Java)
- LeetCode-Two Sum(两数之和)
- 1、Two Sum(两数之和)
- [leetcode, python] Two Sum 两数之和等于某数
- leetcode——Two Sum 两数之和(AC)
- LeetCode 1. Two Sum(两数之和)
- 56.Two Sum-两数之和(中等题)
- 1. Two Sum(两数之和) —— Java
- 371. Sum of Two Integers, 不用加减乘除运算符计算两数之和
- leetcode 1 Two Sum(在无序数组中找两个数之和与目标值相等,两种方法)
- 【LeetCode】- Two Sum(两数相加)
- 1. Two Sum - 两数求和
- [LeetCode]264. Ugly Number II
- Idea+Maven+Jersey2+Tomcat配置Web服务
- java使用TCP协议
- 类的设计
- 【hadoop】hadoop启动后jps无法查看守护进程
- Two sum 两数之和
- Day015
- Mysql建表与索引使用规范整理
- iOS开发网络篇 一一 复杂的JSON解析-数据显示
- 送书福利| Python 完全自学手册
- [论文笔记] CRNN(Convolutional Recurrent Neural Network)_2015 学习笔记
- MongoDB笔记四: C Driver
- 给深度学习入门者的Python快速教程
- jstl <fmt:formatNumber>标签