Two Sum 解答

Question:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Solution:

1. O(n2) runtime, O(1) space – Brute force:

The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).

2. O(n) runtime, O(n) space – Hash table:

We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.

 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
 4         int[] result = new int[2];
 5         int length = nums.length;
 6         for (int i = 0; i < length; i++) {
 7             int left = target - nums[i];
 8             if (hm.get(left) != null) {
 9                 result[0] = hm.get(left) + 1;
10                 result[1] = i + 1;
11             } else {
12                 hm.put(nums[i], i);
13             }
14         }
15         return result;
16     }
17 }

3. O(nlogn) runtime, O(1) space - Binary search

Similar as solution 1, but use binary search to find index2.

4. O(nlogn) runtime, O(1) space - Two pointers

First, sort the array in ascending order vwhich uses O(nlogn).

Then, right pointer starts from biggest number and left pointer starts from smallest number. If two sum is greater than the target number, move the right pointer. If two sum is smaller than the target number, move the left pointer.

原文地址:https://www.cnblogs.com/ireneyanglan/p/4773990.html