标签:style blog http color io os 使用 ar for
Two Sum Problem:
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
解题思路:如果numbers数组已排序,只需用指针i,j分别指向numbers的首尾,并根据sum和target的大小移动指针即可。因此剩下的问题就是对数组排序了。
时间复杂度O(nlbn).
辅助排序算法使用快速排序:
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 }
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 else 26 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 };
标签:style blog http color io os 使用 ar for
原文地址:http://www.cnblogs.com/ym65536/p/4014411.html