zl程序教程

您现在的位置是:首页 >  其他

当前栏目

1.两数之和

2023-04-18 16:11:19 时间

代码:

    public int[] twoSum(int[] nums, int target) {
        int[] res= new int[2];
        if (nums.length<2){
            return res;
        }
        Map<Integer,Integer> keyIndex=new HashMap<>(nums.length);
        for (int i = 0; i < nums.length; i++) {
            if (keyIndex.containsKey(target-nums[i])){
                res[0]=keyIndex.get(target-nums[i]);
                res[1]=i;
                return res;
            }else {
                keyIndex.put(nums[i],i);
            }
        }
        return res;
    }