LeetCode — Two Sum
来源:互联网 发布:keep the windows open 编辑:程序博客网 时间:2024/04/29 06:51
Question:
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
Solution:
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> result; vector<int> new_numbers(numbers); sort(new_numbers.begin(), new_numbers.end()); int head = 0; int tail = new_numbers.size()-1; int indexI = 0; int indexJ = numbers.size() - 1; while(head < tail) { int sum = new_numbers[head] + new_numbers[tail]; if (sum < target) { head++; } else if(sum > target) { tail--; } else { int index1, index2; for(int i = indexI; i < numbers.size(); i++) { if(numbers[i] == new_numbers[head]) { index1 = i + 1; indexI = i + 1; break; } } for(int j = indexJ; j >= 0; j--) { if(numbers[j] == new_numbers[tail]) { index2 = j + 1; indexJ = j - 1; break; } } if(index1 < index2) { result.push_back(index1); result.push_back(index2); } else { result.push_back(index2); result.push_back(index1); } head++; tail--; } } return result; }};
0 0
- LeetCode — Two Sum
- LeetCode—Two Sum
- LeetCode—Two Sum
- leetcode—Two Sum
- LeetCode —-Two Sum
- LeetCode——Two Sum
- LeetCode——Two Sum
- Leetcode —— Two Sum
- LeetCode——Two Sum
- Two Sum —— Leetcode
- LeetCode——Two Sum
- Two Sum —— leetcode
- LeetCode——Two Sum
- LeetCode:Algorith1 —Two Sum
- Sum—LeetCode-1 Two Sum
- 【Leetcode】Two Sum (Sum)
- LeetCode——01 Two Sum
- Python学习——leetcode(Two Sum)
- linux系统考题
- 什么是POJO
- 使用XMPP响应服务器ping包
- Pat(Advanced Level)Practice--1016(Phone Bills)
- C/C++中字符串与数字相互转换
- LeetCode — Two Sum
- Android的基础学习:采用Pull方式解析XML文件(代码)
- 堆排序模板
- 析构函数与虚函数
- 抽象工厂模式
- 欧洲电信标准化协会(ETSI)介绍
- css2.0下 最完美兼容所有浏览器的宽度自适应案例
- SVM入门(八)松弛变量
- QUESTION 30 关于check约束