您的位置:首页 > 其它

个人记录-LeetCode 1.Two Sum

2016-08-14 11:33 411 查看
问题:

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.

代码示例:

1、暴力解法

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

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

return null;
}
}


2、利用hashMap来快速查找

public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
//求出需要的匹配数字
int complement = target - nums[i];
//判断匹配数字是否已经加入到map中
//更快,而且可以避免加入重复数字时HashMap的替换
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode