把以前在GitHub上记录的LeetCode全部挪到这里来。
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
给一个数组找出两个书之和是target数。 可以暴力解法nxn,但肯定超时。
class Solution {
public int[] twoSum(int[] arr, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
int num = target - arr[i];
if (map.containsKey(arr[i])) {
return new int[] { map.get(arr[i]), i };
} else {
map.put(num, i);
}
}
return null;
}
}
用了35分钟完善代码,下次还需提高速度