LeetCode---Two Sum

来源:互联网 发布:ubuntu搭建案桌模拟器 编辑:程序博客网 时间:2024/06/05 14:29

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

解题思路:先对数组进行排序,为了不破坏原始数组,使用一个新的数组来记录原始数组的索引,对索引数组排序,如此一来就相当于对原始数组进行了排序,本文采用堆排序对索引数组进行排序,时间复杂度为N(logN),然后将数组的最后一位与第一位相加,并将结果与Target比对,如果大了,则说明数组的最后一位值过大,此时选择数组的倒数第二位重复上述计算,如果小了,则说明数组的第一位数字小了,因此选择第二位数字重复上述计算,以此类推即可找到与Target相等的值。算法的具体实现如下所示

class Solution {public:vector<int> twoSum(vector<int> &numbers, int target) {vector<int> res;vector<int> index;for(int i=0; i<numbers.size(); i++)index.push_back(i);heap_sort(numbers, index);int n = numbers.size()-1;for(int i=0,j=n;i<j;){if(numbers[index[i]] + numbers[index[j]] > target)j--;else if(numbers[index[i]] + numbers[index[j]] < target)i++;else{if(index[i] < index[j]){res.push_back(index[i]+1);res.push_back(index[j]+1);}else{res.push_back(index[j]+1);res.push_back(index[i]+1);}break;}}return res;}void swap(vector<int>& number, int i, int j){int temp = number[i];number[i] = number[j];number[j] = temp;}void sink(vector<int>& number, vector<int>& index, int loc, int end){int n = end;while(loc < n){int k = 2*loc + 1;if(k > n)break;if(k < n && number[index[k+1]] > number[index[k]])k++;if(number[index[k]] <= number[index[loc]])break;swap(index,k,loc);loc = k;}}void heap_sort(vector<int>& number,vector<int>& index){int n = number.size()-1;for(int i=((n-1)/2); i>=0; i--)sink(number,index,i,n);int i=n;while(i>0){swap(index,0,i);i--;sink(number,index,0,i);}}};




1 0
原创粉丝点击