链接:https://leetcode.cn/problems/two-sum/submissions/
法一:先排序,在排好序的数组中找到对应的两个元素,再在原数组中找这两个元素的位置并返回
缺点:要用多余的数组来存储,以用来排序
时间复杂度:O(nlog2n)
空间复杂度:O(n+logn)
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
void QuickSort(vector<int>& nums,int low,int high){
if(low<high){
int x=Partition(nums,low,high);
QuickSort(nums,low,x-1);
QuickSort(nums,x+1,high);
}
}
int Partition(vector<int>& nums,int low,int high){
int x=nums[low];
while(low<high){
while(low<high && nums[high]>=x) high--;
nums[low]=nums[high];
while(low<high && nums[low]<x) low++;
nums[high]=nums[low];
}
nums[low]=x;
return low;
}
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
vector<int> nums1(nums);
QuickSort(nums1,0,nums1.size()-1);
int low=0,high=nums1.size()-1;
int tar=0;
while(low<high){
tar=nums1[low]+nums1[high];
if(tar<target) low++;
else if(tar>target) high--;
else break;
}
int i;
for(i=0;i<nums.size();i++){
if(nums[i]==nums1[low]) break;
}
result.push_back(i);
if(nums1[low]!=nums1[high]) i=0;
else i+=1;
for(i;i<nums.size();i++){
if(nums[i]==nums1[high]) break;
}
result.push_back(i);
return result;
}
};
int main(){
Solution* obj=new Solution();
vector<int> nums{3,3};
int target=6;
vector<int> result=obj->twoSum(nums,target);
for(auto it=result.begin();it!=result.end();it++) cout<<*it<<" ";
cout<<endl;
return 0;
}
法二:哈希(unordered_map),键存储原数组中的元素,值存储该元素在原数组中的位置。遍历原数组,在hash表中查找是否有键满足key=target-nums[i],若有则返回。unordered_map中find的时间复杂度为O(1),大大缩短查找时间
时间复杂度:O(n)
空间复杂度:O(n)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hashtable;
for(int i=0;i<nums.size();i++){
auto it=hashtable.find(target-nums[i]);
if(it!=hashtable.end()) return{i,it->second};
hashtable[nums[i]]=i;
}
return {};
}
};