Algorithm
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].
Java 程序实现
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[] {map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("no solution");
}
}
Review
布尔表达式索引, 可以根据该索引结构,构建一个简单版本的用户画像的定向广告系统,内存占用低,效率高。定向条件,即数学中DNF表达式。
Tip
充分利用IDE的拼写检查功能,保障英文命名的准确性(宁缺毋滥),否则,到了后期,看着恶心,而修改又风险较大。