挖掘爱站网,网站开发难不难,体育评论做的好的网站,wordpress 爆破用户名当我们需要查询一个元素是否出现过#xff0c;或者一个元素是否在集合里的时候#xff0c;就要第一时间想到哈希法。
C#xff1a;
unordered_map
class Solution {
public: vectorint twoSum(vectorint nums, int target) { unordered_mapint…
当我们需要查询一个元素是否出现过或者一个元素是否在集合里的时候就要第一时间想到哈希法。
C
unordered_map
class Solution {
public: vectorint twoSum(vectorint nums, int target) { unordered_mapint,int m; for(int i 0;inums.size();i) { int s target-nums[i]; auto iter m.find(s); if(iter!m.end()) { return {iter-second,i}; } m.insert(pairint,int(nums[i],i)); } return {}; }
};
Python:
字典
class Solution(object): def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int] result dict() for index,value in enumerate(nums): if target-value in result: return [result[target-value],index] result[value] index return []
集合 result set() for index,value in enumerate(nums): if target-value in result: return [nums.index(target-value),index] result.add(value) return []
C
hashtable
/** * Note: The returned array must be malloced, assume caller calls free(). */
typedef struct { int key; int value; UT_hash_handle hh; // make this structure hashable } map; map* hashMap NULL; void hashMapAdd(int key, int value){ map* s; // key already in the hash? HASH_FIND_INT(hashMap, key, s); if(s NULL){ s (map*)malloc(sizeof(map)); s - key key; HASH_ADD_INT(hashMap, key, s); } s - value value; } map* hashMapFind(int key){ map* s; // *s: output pointer HASH_FIND_INT(hashMap, key, s); return s; } void hashMapCleanup(){ map* cur, *tmp; HASH_ITER(hh, hashMap, cur, tmp){ HASH_DEL(hashMap, cur); free(cur); } } int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{ hashMap NULL; map* hashMapres; int *ans; ans (int*)malloc(sizeof(int)*2); for(int i0;inumsSize;i) { hashMapAdd(nums[i],i); } for(int i0;inumsSize;i) { hashMapres hashMapFind(target-nums[i]); if(hashMapres hashMapres-value!i) { ans[0] i; ans[1] hashMapres-value; *returnSize 2; return ans; } } hashMapCleanup(); return NULL;
}