最小下标两数之和等于目标数(算法)

public int[] addNumber(int[]arr,int target){
    
    int res[] = new int[2];//定义返回下标数组
    Map<Integer,Integer> map = new HashMap<>();

    for(int i=0;i<arr.length;i++){
        if(map.containsKey(target-arr[i])){//当map中存在以组成target的key
            res[0] = map.get(target-arr[i]);
            res[1] = i+1;
            break;
        }else{//插入map中
            map.put(arr[i],i+1);
        }
    }
    return res;
}

代码分析

输入:【3,2,1,4,4,3】6

(1)target-arr[0] = 6-3 = 3;

    map:{【3,1】};

(2)target-arr[1] = 6-2 = 4;

         map:{【3,1】,【2,2】}

(3)target-arr[2] = 6-1 = 5;

         map:{【3,1】,【2,2】,【1,3】}

(4)target-arr[3] = 6-4 = 2;

         res[0] = 2; res[1]=4;

posted @ 2022-01-12 14:35  Q子  阅读(55)  评论(0)    收藏  举报