LeetCode 167. Two Sum II
来源:互联网 发布:网络b类违规是什么意思 编辑:程序博客网 时间:2024/05/16 15:44
167. Two Sum II - Input array is sorted
一、问题描述
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
三、解题思路
- 最简单的方法,遍历数组,找到一个nums[i] 就去遍历剩下的看有没有和为target的,有就返回。时间复杂度是o(n2)
class Solution {public: int hasExpectNum(const vector<int>& numbers, int start, int expect) { int n = numbers.size(); for (int i = start; i < n; ++i) { if(numbers[i] == expect) return i; if(numbers[i] > expect) return -1; } return -1; } vector<int> twoSum(vector<int>& numbers, int target) { int n = numbers.size(); for (int i = 0; i < n; ++i) { int expect = target - numbers[i]; int index = hasExpectNum(numbers, i + 1, expect); if(index != -1){ return vector<int>{i+1, index+1}; } } }};
阅读全文
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]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]167. Two Sum II
- LeetCode 167. Two Sum II
- LeetCode 167. Two Sum II
- LeetCode 167. Two Sum II
- 剑指Offer-16
- stylus之变量(Variables)
- sql查找被锁表名,释放表资源
- idea误删文件恢复方法
- HDU
- LeetCode 167. Two Sum II
- PyTorch学习系列(五)——自定义loss
- 怎样将 MySQL 迁移到 MariaDB 上
- Openvswitch手册(4): Mirror
- VS中相对路径的配置
- hdu1016(一道经典的dfs)
- LeetCode 268. Missing Number
- linux中shell变量$#,$@,$0,$1,$2的含义解释(转载)
- java直接访问链接url,并对返回的json字符串进行解析