• 时间复杂度o(n)
    • 空间复杂度o(n)

    目的就是返回数组中相加等于目标值的数组下标,因此因此,map中键是实际的数组的值。

    1. package TwoNumberSum;
    2. import java.util.HashMap;
    3. import java.util.Map;
    4. public class Sum {
    5. public int[] sum(int[] array, int target) {
    6. //Java当中要求哈希表要初始化,避免扩容带来的损失,最后一个元素不用添加,这个题一定在前面找到对应元素
    7. Map<Integer, Integer> map = new HashMap<>(length-1);
    8. for (int i = 0; i < array.length; i++) {
    9. int temp = target - array[i];//因为这里用到了两遍,习惯
    10. if (map.containsKey(temp)) {
    11. return new int[]{map.get(temp), i};
    12. }
    13. map.put(array[i], i);
    14. }
    15. return new int[]{-1, -1};
    16. }
    17. public static void main(String[] args) {
    18. Sum s = new Sum();
    19. int[] a = {6, 3, 554};
    20. System.out.println(s.sum(a, 9)[0] + " " + s.sum(a, 9)[1]);
    21. }
    22. }

    知识点:不同于String类,String由于实现了常量池 所以new 和不new 有区别:new的话,引用变量指向堆区。不new的话,引用变量指向常量池。
    对于数组的定义,初始化时用new与不用new 没区别 ,只是两种方式罢了,因为数组是引用数据类型,建立对象时,无论用不用new,数组实体都是放在 堆内存中,引用变量放在栈内存。