LeetCode 1. Two Sum

来源:互联网 发布:淘宝兔家公子有假货吗 编辑:程序博客网 时间:2024/06/10 21:08

问题描述:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

问题分析:

给定一个无需的数组nums[],每个值都不一样。给定一个数target。求出两个数的和等于target,要求输出这个两个数的下标。
可以遍历这个数组,先判断target-nums[i]是否在map中,如果在直接返回下标,否者将每个数以及数的下标添加到map中。时间复杂度O(n).

代码实现

public int[] twoSum(int[] nums, int target) {         Map<Integer, Integer> numIndexMap = new HashMap<Integer, Integer>(nums.length);        for (int i = 0; i < nums.length; i++) {            int nextValue = target - nums[i];            if (numIndexMap.get(nextValue) != null) {                return new int[]{numIndexMap.get(nextValue), i};            }            numIndexMap.put(nums[i], i);        }        return new int[2];    }
原创粉丝点击