LeetCode_Two Sum,leetcode_twosum
一.題目Two Sum Total Accepted: 69820 Total Submissions: 386081My Submissions
Given an array of integers, 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
Show TagsHave you met this question in a real interview? Yes No
Discuss
二.解題技巧 這道題最簡單的做法是使用暴力演算法來做,雖然空間複雜度為O(1),但是時間複雜度為O(n^2)。我一開始使用的暴力演算法,結果提交之後直接提示已耗用時間過長,因此,本題的答案並不是暴力演算法。 如果包含有n個元素的數組A是排好序的,設定Head=0, End=n-1, 對於A[Head]+A[End]和目標target,存在下面三種情況:
1.(A[Head]+A[End])==target,那麼A[Head]和A[End]就是能夠滿足條件的兩個元素,判斷結束。2.(A[Head]+A[End])>target, A[End]就不可能是滿足條件的元素,因此,End = End - 1,繼續進行判斷;3.(A[Head]+A[End])<target, A[Head]就不可能是滿足條件的元素,因此,Head = Head + 1,繼續進行判斷;
按照上面的方法,邊界條件是:當Head>=End時,不存在兩個元素的和等於給定的值。 這種方法的時間複雜度O(n),空間複雜度為O(1)。
上面的方法的前提是數組是已經排好序的,對於無序的數組進行排序的時間複雜度為O(nlogn),因此,先對輸入的數組進行排序,然後使用上面的演算法來尋找滿足條件的兩個元素,時間複雜度為O(nlogn)+O(n)=O(nlogn),這樣相對於暴力演算法的O(n^2)的時間複雜度,就大大降低了。
雖然上面的演算法可以找到滿足條件的兩個元素,但是,這道題確實要求計算的是元素的座標,因此,必須先將原來的數組複製一份,然後在複製出來的數組中進行上面的演算法,找到元素之後再在原來的數組中尋找座標的值。 由於數組中可能存在相同的元素,並且滿足條件的兩個元素是相同的,因此,在找到第一個元素的座標之後,需要更改第一個元素的值,為了方便起見,可以將第一個元素的值更改為第二個元素減去1,然後再尋找第二個元素的座標。
三.實現代碼
class Solution{public: vector<int> twoSum(vector<int> &numbers, int target) { // copy the numbers vector<int> TmpNumbers(numbers); // sort the tmp number vector sort(TmpNumbers.begin(), TmpNumbers.end()); int Size = TmpNumbers.size(); int HeadIndex = 0; int EndIndex = Size - 1; int Start = 0; int End = 0; int SumOfTwo = 0; while(HeadIndex < EndIndex) { Start = TmpNumbers[HeadIndex]; End = TmpNumbers[EndIndex]; SumOfTwo = Start + End; if (SumOfTwo == target) { break; } if (SumOfTwo > target) { EndIndex--; } if (SumOfTwo < target) { HeadIndex++; } } // find the element vector<int>::iterator Ite_1 = find(numbers.begin(), numbers.end(), Start); (*Ite_1) = End - 1; vector<int>::iterator Ite_2 = find(numbers.begin(), numbers.end(), End); // get the index of the element int Index_1 = Ite_1 - numbers.begin() + 1; int Index_2 = Ite_2 - numbers.begin() + 1; if (Index_1 > Index_2) { int Tmp = Index_1; Index_1 = Index_2; Index_2 = Tmp; } vector<int> Result; Result.push_back(Index_1); Result.push_back(Index_2); return Result; }};
四.體會 這道題也是一道利用排序的數組的特性的題,只不過原始的數組是沒有排序的,對原始數組進行排序之後,就可以利用排序數組的特性進行計算了。這道題也算是一道比較簡單的題目了。
著作權,歡迎轉載,轉載請註明出處,謝謝