leetcode_01_Two sum
来源:互联网 发布:sql编写存储过程 编辑:程序博客网 时间:2024/05/21 07:46
欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢
Two sum
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
/* 方法一:排序1 把原始数据排序2 用两个指标start和end从数组两头往中间走,如果两个当前数字的和比目标数字小,那么start往后走一位。如果两个当前数字的和比目标数字大,那么end往前走一位。如果两个当前数字的和等于目标数,那么我们就得到了start和end的指标。3 找到start和end所对应数字在原始数组中的位置*/class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> result; vector<int> temp = numbers; sort(temp.begin() , temp.end()); int start = 0 , end = temp.size()-1; while(temp[start] + temp[end] != target) { if(temp[start] + temp[end] < target) start++; else end--; } int i = 0; while(numbers[i] != temp[start]) { i++; } result.push_back(i+1); int j = numbers.size()-1; while(numbers[j] != temp[end]) { j--; }/*可能输出的下标位置会变成倒序Input:[5,75,25], 100Output:3, 2Expected:2, 3*/ if(result[0] <= j+1) result.push_back(j+1); else result.insert(result.begin() , j+1);//插入到begin()之前 return result; }};
/*方法二:Map<K, V>为<值,下标>,map中保存的是已经扫描过的number。这是一种很直观很自然的做法:对于numbers[i],如果map中存在K=target-numbers[i],则要求的解为V(K=target-numbers对应的)和i;如果不存在,则向map中添加<numbers[i], i>。*/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; }};
1 0
- leetcode_01_Two sum
- Sum
- sum
- sum
- Sum
- Sum
- Sum
- sum
- Sum
- sum
- Sum
- sum
- Sum
- sum
- Sum Sum Sum
- HDU5150 Sum Sum Sum
- HDU - 5150 Sum Sum Sum
- hdu 5150 sum sum sum
- Unity性能优化之Draw Call
- 使用JNotify监控硬盘
- hdu 3746 Cyclic Nacklace (kmp扩展—最小循环节)
- 日语五十音图。
- IOS 应用内购买
- leetcode_01_Two sum
- Android 解决点击EditText获取焦点时输入法占满手机屏幕的办法
- 浅谈实战中销售信的写作
- Oracle dblink详解
- 设计包含min函数的栈
- 游戏服务端pomelo完整安装配置过程
- mysql数据迁移
- 029 弦截法求根
- Java基础——自定义Annotation