LeetCode - 1. 两数之和

1. 两数之和

import java.util.*;

class Solution {

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> indexHash = new HashMap<>();
        int[] result = new int[2];
        for (int i = 0; i < nums.length; ++ i) {
            Integer x = indexHash.get(target - nums[i]);
            if (Objects.nonNull(x)) {
                result[0] = x;
                result[1] = i;
                break;
            }
            indexHash.put(nums[i], i);
        }
        return result;
    }
}


猜你喜欢

转载自blog.51cto.com/tianyiya/2171984