一直听说LeetCode,今天第一次刷题,之前没有接触过算法,记录自己的刷题。
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]
思路:两个数整数相加等于targe,且数组中都为大于零,故需要查找targe-x的位置
解法:
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
int temp = nums[i];
if (map.containsKey(temp)) {
result[0] = map.get(temp);
result[1] = i;
return result;
}
//如果没有,就put到map里面
else {
map.put(target - nums[i], i);
}
}
throw new IllegalArgumentException("No two sum solution");
}
这道题作为第一题还是很简单的,开始想把数组通过asList转为List,通过indexof去查找targe-x的位置。 后来突然想到8 个基本类型是无法作为 asList 的参数的。 所以换成map