LeetCode-1. Two Sum

来源:互联网 发布:萍乡网络小额贷款公司 编辑:程序博客网 时间:2024/05/29 18:38

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.

意思就是给一个数组,和一个target,找到数组中的两个数,这两个数的和等于target,返回数组中两个数的下标

如果利用暴力遍历法,时间复杂度为n^2,这里用hsah表法,可以把时间复杂度降到n,以数组的值为key,下标为值放入hash表中,比如有数组{2,7,11,5} target=9

第一步map.put(2,0)

第二步,当要put(7,1)之前,先检查map中有没有key=target-7的键值对,如果有则说明已经存在两个数满足和等于target,则返回它们的下标。

import java.util.*;class Solution {    public static int[] twoSum(int[] nums, int target)    {        int index1=0;        int index2=0;        Map<Integer,Integer> map=new HashMap<Integer,Integer>();        int a[]=null;        for(int i=0;i<nums.length;i++)        {            if(map.containsKey(target-nums[i]))                a=new int[]{map.get(target-nums[i]),i};            map.put(nums[i],i);        }        return a;    }    public static void main(String []args)    {        int []a={2,7,11,15};        int target=9;        int []b=twoSum(a,target);        System.out.println(b[0]+"----------"+b[1]);    }}


原创粉丝点击