Easy 1题 Two Sum

来源:互联网 发布:mysql 分组 字段累加 编辑:程序博客网 时间:2024/05/16 09:09

问题:

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].

很容易用O(N^2)解,但是没想到用hash表,so the hint is just like below...

public class Solution {    public int[] twoSum(int[] nums, int target) {    /*    int i,j;        int result[]=new int[2];        for(i=0;i<=nums.length-1;i++)        {            for(j=i+1;j<=nums.length-1;j++)            {                if(target==nums[i]+nums[j])                {                    result[0]=j;                    result[1]=i;                    break;                }            }        }        return result;        */        int[] result = new int[2];        Map<Integer, Integer> map = new HashMap<Integer, Integer>();        for(int i=0;i<=nums.length-1;i++)        {            if(map.containsKey(target-nums[i]))//若找到则结束,返回存储的下标+1和当前下标+1.            {                result[1]=i+1;                 result[0]=map.get(target-nums[i]); //找回原来存的下标                break;            }            else//若找不到则将<nums[i], i>加入映射表。            {                map.put(nums[i], i+1);            }        }        return result;       }}


0 0