LeetCode题解——1. 两数之和

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map</*数组中的值*/Integer, /*数组中的值对应的下标*/Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }

        // 不存在满足要求的,则返回默认结果
        return new int[]{0, 0};
    }
}

评论

暂无评论