【LeetCode】1 Two Sum

来源:互联网 发布:景区网络销售专员 编辑:程序博客网 时间:2024/06/05 06:56

HashMap

/** * Given an array of integers, find two numbers such that they add up to a * specific target number. * <p> * 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. * <p> * You may assume that each input would have exactly one solution. * <p> * Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 */public class Solution {    public int[] twoSum(int[] nums, int target) {        int [] index = new int [2];        Map<Integer,Integer> map = new HashMap<Integer,Integer>();        for(int i=0;i<nums.length;i++)        {            if(map.containsKey(nums[i]))            {                index[0] = map.get(nums[i])+1;                index[1] = i+1;                return index;            }            else            {                map.put(target-nums[i], i);            }        }        return index;    }}

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).

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.

0 0
原创粉丝点击