LeetCode / 3 min read
LeetCode - 1. TwoSum
LeetCode - 1. TwoSum
On this page
題目 1. Two Sum
找出相加等於target的兩數。
解題思路
題目自帶官方解法。
Code
Java
Runtime 2 ms, Memory 42.7 MB
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } return null; }}Python3
Runtime 56 ms,Memory 15.2 MB
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashmap = {} for i in range(len(nums)): complement = target - nums[i] if complement in hashmap: return [i, hashmap[complement]] hashmap[nums[i]] = iC#
Runtime 146 ms, Memory 44.8 MB
public class Solution { public int[] TwoSum(int[] nums, int target) { Dictionary<int, int> map = new Dictionary<int, int>(); for(int i = 0; i < nums.Length; i++){ int num = nums[i]; int complement = target - num; if (map.ContainsKey(complement)){ return new int[] {map[complement], i}; }else if(!map.ContainsKey(num)){ map.Add(num, i); } } return null; }}Golang
Runtime 9 ms, Memory 4.2 MB
func twoSum(nums []int, target int) []int { mapNum := make(map[int]int) for i, num := range nums{ var complement int = target - num // check val is in map if val, ok := mapNum[complement]; ok { return []int{i, val} } mapNum[num] = i } return nil}C++
Runtime 9 ms, Memory 11.2 MB
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { map<int, int> mapNum; for(int i = 0; i < nums.size(); i++){ int num = nums[i]; int complement = target - num; if (mapNum.count(complement) > 0){ return {mapNum[complement], i}; } else { mapNum.insert({num, i}); } } return {-1, -1}; }};C
Runtime ms, Memory MB Reference
struct number_hash { int value; int index; UT_hash_handle hh;};void destroy_table(struct number_hash** table) { struct number_hash* curr; struct number_hash* tmp; HASH_ITER(hh, *table, curr, tmp) { HASH_DEL(*table, curr); free(curr); }}int* twoSum(int* nums, int numsSize, int target, int* returnSize) { struct number_hash* table = NULL; struct number_hash* element; int* ret = (int*) malloc(2 * sizeof(int)); int remaining; for (int i = 0; i < numsSize; ++i) { remaining = target - nums[i]; // Find if there has already been an element such that the sum is target HASH_FIND_INT(table, &remaining, element); if (element) { ret[0] = element->index; ret[1] = i; break; } // Add the new number to the hash table if it doesn't exist already HASH_FIND_INT(table, &nums[i], element); if (!element) { element = (struct number_hash *) malloc(sizeof(*element)); element->value = nums[i]; element->index = i; HASH_ADD_INT(table, value, element); } } destroy_table(&table); *returnSize = 2; return ret;}