算法之循环
查找表法
在遍历的同时记录一些信息,以省去一层循环,这就是“以空间换取时间”的想法。
查找表法有俩个常用的实现:
- 哈希表法
- 平衡二叉搜索树(对元素顺序有要求的可用)
实现可以看链接中的哈希表实现降低复杂度:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-solution/
public static int[] twoSumPro(int[] nums, int target) {
HashMap<Integer, Integer> hashtable = new HashMap<>(nums.length - 1);
hashtable.put(nums[0], 0);
for (int i = 1; i < nums.length; i++) {
int another = target - nums[i];
if (hashtable.containsKey(another)) {
return new int[]{i, hashtable.get(another)};
}
hashtable.put(nums[i], i);
}
throw new IllegalArgumentException("no two sum to solution");
}