• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C++实现LeetCode(167.两数之和之二 – 输入数组有序)

c++ 搞代码 4年前 (2022-01-06) 29次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了C++实现LeetCode(167.两数之和之二 – 输入数组有序),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

[LeetCode] 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 t来源gaodai#ma#com搞@@代~&码网woSum 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

这又是一道Two Sum的衍生题,作为LeetCode开山之题,我们务必要把Two Sum及其所有的衍生题都拿下,这道题其实应该更容易一些,因为给定的数组是有序的,而且题目中限定了一定会有解,我最开始想到的方法是二分法来搜索,因为一定有解,而且数组是有序的,那么第一个数字肯定要小于目标值target,那么我们每次用二分法来搜索target – numbers[i]即可,代码如下:

解法一:

 // O(nlgn) class Solution { public: vector twoSum(vector& numbers, int target) { for (int i = 0; i <numbers.size(); ++i) { int t = target - numbers[i], left = i + 1, right = numbers.size(); while (left <right) { int mid = left + (right - left) / 2; if (numbers[mid] == t) return {i + 1, mid + 1}; else if (numbers[mid] <t) left = mid + 1; else right = mid; } } return {}; } };

但是上面那种方法并不efficient,时间复杂度是O(nlgn),我们再来看一种O(n)的解法,我们只需要两个指针,一个指向开头,一个指向末尾,然后向中间遍历,如果指向的两个数相加正好等于target的话,直接返回两个指针的位置即可,若小于target,左指针右移一位,若大于target,右指针左移一位,以此类推直至两个指针相遇停止,参见代码如下:

解法二:

 // O(n) class Solution { public: vector twoSum(vector& numbers, int target) { int l = 0, r = numbers.size() - 1; while (l <r) { int sum = numbers[l] + numbers[r]; if (sum == target) return {l + 1, r + 1}; else if (sum <target) ++l; else --r; } return {}; } };

类似题目:

Two Sum III – Data structure design

Two Sum

参考资料:

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/

以上就是C++实现LeetCode(167.两数之和之二 – 输入数组有序)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++实现LeetCode(167.两数之和之二 – 输入数组有序)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址