Two Sum

来源:互联网 发布:php 上传类 编辑:程序博客网 时间:2024/04/19 13:19

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.
Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

Solution

public class Solution {    public int[] twoSum(int[] nums, int target) {        Map<Integer, Integer> map = new HashMap<Integer, Integer>();        int[] rs = new int[2];        for(int index = 0; index < nums.length; index++){            map.put(nums[index], index);        }        for(int index = 0; index < nums.length; index++){            if(map.get(target-nums[index]) != null && index != map.get(target-nums[index])){                rs[0] = index;                rs[1] = map.get(target-nums[index]);                break;            }        }        return rs;    }}
0 0
原创粉丝点击