leetcode Two Sum II
来源:互联网 发布:java项目的工作流程 编辑:程序博客网 时间:2024/05/16 17:25
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
Output: index1=1, index2=2
题意:给定有序数组和一个目标数,从数组中找到两个数的和为目标数。
1、最容易想到的思路—遍历,时间复杂度O(n^2);
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { int index1 = 0; int index2 = 0; int flag = 0; for(; index1 < numbers.size() - 1; ++index1) { int temp = target - numbers[index1]; flag = 0; for (index2 = index1+1; index2 < numbers.size(); index2++) { if (temp == numbers[index2]){ flag = 1; break; } } if(flag) break; } if(flag) { vector<int> ans; ans.push_back(index1+1); ans.push_back(index2+1); return ans; } //return; }};
2、思路:由于数组是有序的,定义两个下标,一个指向最小数,一个指向最大数,若它们的和大于目标数,则右侧下标左移,若它们的和小于目标数,则左侧下标右移。时间复杂度O(n);
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { int low=0, high=numbers.size()-1; while (numbers[low]+numbers[high]!=target){ if (numbers[low]+numbers[high]<target){ low++; } else { high--; } } return vector<int>({low+1,high+1}); }};
阅读全文
0 0
- [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】【python】Two Sum, 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 | 167. Two Sum II
- Bootstrap Table使用分享
- Java复习笔记+经验总结-05 集合框架 IO流
- 测试微信邀请码
- 数据结构实验之链表三:链表的逆置
- 【Java基础03】数组及其遍历、最值、反转、查表和基本查找
- leetcode Two Sum II
- 图像的卷积
- Linux文本编辑器Vim
- 深入理解Cache
- AJAX学习笔记(五)_AJAX响应
- Java工程师学习路线
- 右对齐(Right-to-Left)语言导致的问题(如:阿拉伯语)
- ???题目5 : Territorial Dispute
- 依赖类型dependency type在maven中的作用