[LeetCode] 1.Two Sum, leetcode1.twosum
[Question]
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum shocould 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 wowould have exactly one solution.
Input: numbers = {2, 7, 11, 15}, target = 9
Output: index1 = 1, index2 = 2
[Analysis]
It is similar to two numbers for the sum of the sword and the Offer.
[Code]
/********************************** Date: * Author: SJF0115 * Subject: 1.Two Sum * URL: https://oj.leetcode.com/problems/two-sum/* result: AC * Source: LeetCode * blog: * *********************************/# include <iostream> # include <algorithm> # include <vector> using namespace std; class Solution {public: vector <int> twoSum (vector <int> & numbers, int target) {vector <int> result; vector <int> num = numbers; int count = numbers. size (); if (numbers. empty () {return result;} // if // sort (numbers. begin (), numbers. end (); // Binary Search deformation for (int I = 0, j = count-1; I <j ;) {int sum = numbers [I] + numbers [j]; // locate the target if (sum = target) {return FindIndex (num, numbers [I], numbers [j]);} // current and greater than the target, else if (sum> target) {j --;} // current and smaller than the target, else {I ++ ;}// for return result ;}private: // search for subscript vector <int> FindIndex (vector <int> & numbers, int num1, int num2) {int count = numbers. size (); vector <int> result; int index1, index2; bool flag1 = false, flag2 = false; for (int I = 0; I <count; ++ I) {if (flag1 = false & numbers [I] = num1) {index1 = I + 1; flag1 = true ;} else if (flag2 = false & numbers [I] = num2) {index2 = I + 1; flag2 = true ;}} /// for // enable index1 <index2 if (index1> index2) {int tmp = index1; index1 = index2; index2 = tmp;} // if result. push_back (index1); result. push_back (index2); return result ;}}; int main () {Solution solution; vector <int> num; num. push_back (0); num. push_back (4); num. push_back (3); num. push_back (0); // num. push_back (15); int target = 0; // search for vector <int> vec = solution. twoSum (num, target ); // output cout <"Index1->" <vec [0] <"Index2->" <vec [1] <endl; return 0 ;}