C++實(shí)現(xiàn)LeetCode(167.兩數(shù)之和之二 - 輸入數(shù)組有序)
[LeetCode] 167.Two Sum II - Input array is sorted 兩數(shù)之和之二 - 輸入數(shù)組有序
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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
這又是一道Two Sum的衍生題,作為LeetCode開山之題,我們務(wù)必要把Two Sum及其所有的衍生題都拿下,這道題其實(shí)應(yīng)該更容易一些,因?yàn)榻o定的數(shù)組是有序的,而且題目中限定了一定會(huì)有解,我最開始想到的方法是二分法來搜索,因?yàn)橐欢ㄓ薪猓覕?shù)組是有序的,那么第一個(gè)數(shù)字肯定要小于目標(biāo)值target,那么我們每次用二分法來搜索target - numbers[i]即可,代碼如下:
解法一:
// O(nlgn)
class Solution {
public:
vector<int> twoSum(vector<int>& 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,時(shí)間復(fù)雜度是O(nlgn),我們?cè)賮砜匆环NO(n)的解法,我們只需要兩個(gè)指針,一個(gè)指向開頭,一個(gè)指向末尾,然后向中間遍歷,如果指向的兩個(gè)數(shù)相加正好等于target的話,直接返回兩個(gè)指針的位置即可,若小于target,左指針右移一位,若大于target,右指針左移一位,以此類推直至兩個(gè)指針相遇停止,參見代碼如下:
解法二:
// O(n)
class Solution {
public:
vector<int> twoSum(vector<int>& 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
參考資料:
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(167.兩數(shù)之和之二 - 輸入數(shù)組有序)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)兩數(shù)之和之二 - 輸入數(shù)組有序內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++實(shí)現(xiàn)LeetCode(174.地牢游戲)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(174.地牢游戲),本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
C++?std::copy與memcpy區(qū)別小結(jié)
本文主要介紹了C++?std::copy與memcpy區(qū)別小結(jié),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-05-05
c++如何控制輸出浮點(diǎn)數(shù)小數(shù)點(diǎn)后若干位
這篇文章主要介紹了c++如何控制輸出浮點(diǎn)數(shù)小數(shù)點(diǎn)后若干位問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
簡單比較C語言中的execl()函數(shù)與execlp()函數(shù)
這篇文章主要介紹了C語言中的execl()函數(shù)與execlp()函數(shù)的簡單比較,是C語言入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-08-08

