您的位置:首页 > 编程语言 > Java开发

LeetCode(java)1. Two Sum

2016-04-06 12:45 363 查看
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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

一开始的解法为穷举法:时间复杂度为O(n²)

public class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++)
{
for(int j=i+1;j<nums.length;j++)
{
if(nums[i]+nums[j] == target)
return new int[]{i+1,j+1};
}
}

return null;
}
}
后来发现有点慢:改进了算法,使用了HashMap,时间复杂度变为O(n),通过时间为7ms

public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
Integer lc;
for(int i=0;i<nums.length;i++)
{
map.put(nums[i], i);
}
for(int i=0;i<nums.length;i++)
{
if((lc = map.get(new Integer(target-nums[i])))!=null)
{
if(lc!=i)
return new int[]{i,lc};
}
}

return null;
}
}


其实如果不惜内存的话可以建立两个超大的数组,第一个用于存放正数(例如7则将arr[7]置1),另一个存放负数(例如-11则将arrsc[11]置1)。

数组的操作应该比HashMap更快
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Two Sum