/*
又学了一个stl,hashmap
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int, int> hash_map;
//遍历整个表,如果当前没有找到就将其加入到hash_map
for(int i=0;i<nums.size();i++){
//查找成功
if(hash_map.find(target-nums[i]) != hash_map.end()){
res.push_back(hash_map[target-nums[i]]);
res.push_back(i);
}
hash_map[nums[i]]=i;
}
return res;
}
};
其实这道题用map也能过,map和hash_map的区别在于数据结构不同,时间复杂度不同,map的实现是红黑树,hash_map的实现是哈希函数。map查找的复杂度基本上是O(logN),hash_map的时间复杂度常规情况是常数级,但是如果哈希函数不够好,产生的碰撞太多,时间复杂度会比较高。
思路:首先将序号和数值在一个结构体中存下来,排序后,然后遍历一遍,每次遍历过程中二分查找另外一个数字。
二分查找
vector
结构体的sort
*/
class Solution {
public:struct Node{
int val;
int num;
}node[100000];
static bool cmp(struct Node n, struct Node m){ //升序
if(n.val<m.val) return true;
else return false;
}
//二分查找
int binarySearch(struct Node array[], int key, int len){
int l = 0, r = len-1;
while(l<=r){
int mid = (l+r)>>1;
if(array[mid].val == key) return mid;
else if(array[mid].val < key) l = mid+1;
else r = mid-1;
}
return -1; //查找失败
}
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
vector<int> result;
for(int i=0;i<len;i++){
node[i].val=nums[i];
node[i].num=i;
}
sort(node,node+len,cmp);
for(int i=0;i<len;i++){
int k = target - node[i].val;
//二分查找
int j = binarySearch(node, k, len);
//查找成功
if(j!=-1 && j!=i){
int a = node[i].num;
int b = node[j].num;
result.push_back(a<b?a:b);
result.push_back(a>b?a:b);
break;
}
}
return result;
}
};