Closed SummerXinBing closed 4 months ago
使用hash
// 本质还是搜索target-x;但是使用数据结构将时间复杂度降到o(n),hash的搜索o(1)
// map的两个api boolean containKey(Object key) boolean containValue(Object value)
public static int[] twoSum(int[] nums, int target) {
int length = nums.length;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i = 0; i < length; i++) {
int x = nums[i];
if (map.containsKey(target - x)) {
return new int[]{i,map.get(target-x)};
}
map.put(x,i);
}
return new int[0];
}
暴力解决 时间复杂度o(n^2) 空间复杂度o(1)