1_Two Sum
[easy] [array, hash table]
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the_same_element twice.
Example:
Solution 1: brute force
Fix the position of the first number, and search for the second number that satisfy the condition.
Time Complexity:
Space Complexity:
Solution 2: sort + two pointers
Sort the numbers first, then use two pointers to find the pair.
Time Complexity:
Space Complexity:
Solution 3: dictionary
Check elements in the array one by one. Use a dictionary to store information for future checking of the next element.Key is target - element. Value is the index. Such that for every next element, search if it exists in the dictionary.If it does, return the value we find and the index for current element. Otherwise add new key-value pair into the dictionary.
The key point is to use dictionary instead of array. Searching in dictionary is O(1). Searching in arrary is O(n).
Time Complexity:
Space Complexity:
Last updated