查找和为某值的两个数
来源:互联网 发布:中国原创服装品牌 知乎 编辑:程序博客网 时间:2024/04/29 01:38
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
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> temp(numbers); sort(temp.begin(), temp.end()); vector<int> result; int value1; int value2; int left = 0; int right = temp.size() - 1; bool found = false; while (left < right) { int sum = temp[left] + temp[right]; if (sum == target) { found = true; value1 = temp[left];; value2 = temp[right]; break; } else if (sum > target) { right--; } else { left++; } } if (found) { int pos1 = -1; int pos2 = -1; int size = numbers.size(); for (int i = 0; i < size; i++) { if (numbers[i] == value1) { pos1 = i+1; break; } } for (int i = size-1; i >= 0; i--) { if (numbers[i] == value2) { pos2 = i+1; break; } } result.push_back(pos1); if (pos2 > pos1) { result.push_back(pos2); } else { result.insert(result.begin(), pos2); } } return result; }};
0 0
- 查找和为某值的两个数
- 查找和为某一值的两个数
- 查找数组中和为某给定值的两个数
- 有序数列中查找和为某定值的两个数
- 笔试面试之有序数组中查找和为定值的两个数
- 在给定数组中查找两个数的和为给定值sum
- 【100题】在排序数组中查找和为给定值的两个数
- 在数组中查找和为定值的两个数
- 排序数组中查找和为给定值的两个数O(n)
- 【Data Structure & Algorithm】在排序数组中查找和为定值的两个数
- 数据结构学习笔记6-寻找和为定值的两个数(二分查找)
- 查找数组中和为特定值的两个数
- 在一个排好序的数组中查找和为sum的两个数
- 【扩展】快速寻找满足条件(两个数的和为指定值)的两个数
- 寻找两个数的和为定值的算法
- 面试100题:14.求在有序数组中查找两个数的和为指定数
- 面试100题:14.求在有序数组中查找两个数的和为指定数
- 查找和为0的三个数
- SQL 左外连接,右外连接,全连接,内连接
- ss2H框架常遇到的错误记录
- Java:单例模式的七种写法
- 多线程编程3 - NSOperationQueue
- Longest Substring Without Repeating Characters
- 查找和为某值的两个数
- LeetCode: Intersection of Two Linked Lists
- 杭州女子朋友圈卖假货面对惩罚 买家心照不宣
- 应用DOM4J解析节点信息
- LeetCode-3Sum
- windbg分析dump文件
- Shader_0
- Loon游戏引擎(LGame)开发者鹏大重现江湖,目测又将改写Java界
- 黑马程序员————C语言基础 第13篇 字符串知识总结