您的位置:首页 > 编程语言 > Go语言

【LeetCode】1 Two Sum

2015-07-02 14:21 507 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm