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

leetcode Two Sum(Java)

2017-06-05 16:19 295 查看
题目链接:https://leetcode.com/problems/two-sum/#/description

遍历问题

暴力解法:遍历数组,算法复杂度O(n²)

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


hashMap:虽然少了一次循环,但是HashMap的查找value值仍需要额外的时间

public class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length < 1)
return new int[]{-1, -1};

HashMap<Integer, Integer> test = new HashMap<Integer, Integer>();
for(int i = 0 ; i < nums.length ; ++i)
{
int complement = target-nums[i];
if(test.containsKey(complement))
{
return new int[]{test.get(complement), i};
}
else
{
test.put(nums[i], i);
}
}
return new int[]{-1, -1};
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: