- 时间复杂度o(n)
- 空间复杂度o(n)
目的就是返回数组中相加等于目标值的数组下标,因此因此,map中键是实际的数组的值。
package TwoNumberSum;import java.util.HashMap;import java.util.Map;public class Sum {public int[] sum(int[] array, int target) {//Java当中要求哈希表要初始化,避免扩容带来的损失,最后一个元素不用添加,这个题一定在前面找到对应元素Map<Integer, Integer> map = new HashMap<>(length-1);for (int i = 0; i < array.length; i++) {int temp = target - array[i];//因为这里用到了两遍,习惯if (map.containsKey(temp)) {return new int[]{map.get(temp), i};}map.put(array[i], i);}return new int[]{-1, -1};}public static void main(String[] args) {Sum s = new Sum();int[] a = {6, 3, 554};System.out.println(s.sum(a, 9)[0] + " " + s.sum(a, 9)[1]);}}
知识点:不同于String类,String由于实现了常量池 所以new 和不new 有区别:new的话,引用变量指向堆区。不new的话,引用变量指向常量池。
对于数组的定义,初始化时用new与不用new 没区别 ,只是两种方式罢了,因为数组是引用数据类型,建立对象时,无论用不用new,数组实体都是放在 堆内存中,引用变量放在栈内存。
