两数之和

LeetCode刷题:两数之和

package LeetCode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class demo01 {
    public static int[] twoSum(int[] arr,int target){
        Map<Integer,Integer> map=new HashMap<>();   //key:数  value:位置(索引)
        for (int i=0;i<arr.length;i++){
            if (map.containsKey(target-arr[i])){
                return new int[]{map.get(target-arr[i]),i};
            }else {
                map.put(arr[i],i);
            }
        }
        return new int[]{-1,-1};  //找不到是返回[-1,-1]
    }
    public static void main(String[] args) {
        int[] arr={1,2,8,7,9};
        int[] twoSum = twoSum(arr, 10);
        System.out.println(Arrays.toString(twoSum));

    }
}

 

上一篇:微信小程序实现时间的实时跳动


下一篇:java黑皮书课后习题7.14