LeetCode[167]Two Sum II
来源:互联网 发布:js获取今天年月日 编辑:程序博客网 时间:2024/05/22 14:54
Given an array of integers that is already sorted in ascending order, 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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
提交程序:
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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
本地可运行程序:
#include<iostream>#include<vector>using namespace std;/*解题思路是先首尾相加,然后相加的值与目标值对比,比目标值小的话,首向右移动,比目标值大的话,尾向左移动。因为数值是从小到大排列,所以这种方法刚好解题。*/vector<int> twoSum(vector<int>& numbers, int target);int main(){vector<int> numbers = { 2,7,11,15 };int target = 9;vector<int> result;result = twoSum(numbers, target);for (int i = 0; i < result.size(); i++){cout << result[i] << endl;}system("pause");return 0;}vector<int> twoSum(vector<int>& numbers, int target){vector<int> result;int i = 0;//首索引int j = numbers.size() - 1;//尾索引while (target-numbers[i] != numbers[j]){if (target - numbers[i] > numbers[j]){i++;//相加值比目标值小,首向右移动}else{j--;//相加值比目标值大,尾向左移动}}result.push_back(i+1);result.push_back(j+1);return result;}
提交程序:
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> result; int i = 0; int j = numbers.size() - 1; while (target-numbers[i] != numbers[j]) { if (target - numbers[i] > numbers[j]) { i++; } else { j--; } } result.push_back(i+1); result.push_back(j+1); return result; }};
阅读全文
0 0
- Leetcode #167 Two Sum II
- Leetcode 167 Two Sum II
- LeetCode 167 Two Sum II
- LeetCode[167]Two Sum II
- LeetCode-167:Two Sum II
- leetcode 167--- Two Sum II
- LeetCode #167 Two Sum II
- [leetcode] Two Sum II
- LeetCode : Two Sum II
- leetcode [Two Sum II
- 【LeetCode】Two Sum II
- 【leetcode】Two Sum II
- LeetCode:Two Sum II
- leetcode--Two Sum II
- leetcode Two Sum II
- leetcode -- Two Sum II
- leetCode-Two Sum II
- [Leetcode]1(167). Two Sum I, II
- hanoi塔
- 移动端事件基础
- dcsd
- UWP开源项目 LLQNotifier 页面间通信利器(移植EventBus)
- C++中的异常处理(三)
- LeetCode[167]Two Sum II
- 三十年河东三十年河西
- TeamViewer不小心注册成商业版试用期到期怎么办
- 使用 DialogFragment 和 BottomSheet 实现底部弹出框
- Spring 报 NoSuchBeanDefinitionException
- 技术文章 | 深入剖析:关于cache buffers chains的经典案例处理详解
- 解决 CPU topology doesn't match maximum vcpu count
- 大化设计模式-单例模式
- n皇后,排列树