第一次使用HashMap

来源:互联网 发布:四轴叶轮加工编程方法 编辑:程序博客网 时间:2024/06/06 03:03

题目描述

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
我的代码如下:

import java.util.*;public class twosum {    public static void main(String[] args) {        // TODO Auto-generated method stub        Scanner sc=new Scanner(System.in);            String[] A=sc.nextLine().split(" ");            int target=sc.nextInt();            int[] num=new int[A.length];            for(int i=0;i<A.length;i++){                num[i]=Integer.parseInt(A[i]);            }            int[] sum=hashMapTwoSum(num,target);            System.out.println(sum[0]+" "+sum[1]);    }    static int[] hashMapTwoSum(int[] numbers,int target){        int[] sum=new int[2];        HashMap<Integer,Integer>map=new HashMap<Integer,Integer>();        for(int i=0;i<numbers.length;i++){            if(map.containsKey(numbers[i])){                sum[0]=map.get(numbers[i])+1;                sum[1]=i+1;            }            else{                map.put(target-numbers[i], i);            }        }        return sum;    }}
0 0
原创粉丝点击