Two sum problem:
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
Solution: if the numbers array is sorted, you only need to use the pointer I and j to point to the beginning and end of numbers respectively, and move the pointer according to the sum and target sizes. Therefore, the remaining problem is to sort the array.
Time complexity O (nlbn ).
Secondary sorting algorithms use quick sorting:
1 #define exchange(a, b, type) do {type temp = a; a = b; b = temp;}while (0) 2 struct Node 3 { 4 int num; 5 int pos; 6 }; 7 8 int partition(Node A[], int p, int r) 9 {10 int left = p, right = r;11 int povit = A[p].num;12 13 while (left < right)14 {15 while ((left <= r) && (A[left].num <= povit))16 left++;17 while ((right >= p) && (A[right].num > povit))18 right--;19 if (left < right)20 exchange(A[left], A[right], Node);21 }22 exchange(A[right], A[p], Node);23 return right;24 }25 26 void quick_sort(Node A[], int p, int r)27 {28 int q;29 if (p < r)30 { 31 q = partition(A, p, r); 32 quick_sort(A, p, q - 1); 33 quick_sort(A, q + 1, r); 34 } 35 }
View code
Solution:
1 class Solution 2 { 3 public: 4 vector<int> twoSum(vector<int> &numbers, int target) 5 { 6 int i,j, sum; 7 int n = numbers.size(); 8 vector <int> result; 9 struct Node *array = new Node[n];10 for (i = 0; i < n; i++)11 {12 array[i].num = numbers[i];13 array[i].pos = i;14 }15 16 quick_sort(array, 0, n-1);17 18 i = 0;19 j = n - 1;20 sum = array[i].num + array[j].num;21 while (sum != target)22 {23 if (sum > target)24 j--;25 else26 i++;27 sum = array[i].num + array[j].num;28 }29 result.push_back(min(array[i].pos, array[j].pos) + 1);30 result.push_back(max(array[i].pos, array[j].pos) + 1);31 32 delete []array;33 return result;34 }35 };
Leetcode 1.Two sum