TwoSum两个数的和

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

题目大意

 

  给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。
  要求:这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。请注意一点,你返回的结果(包括index1和index2)都不是基于0开始的。你可以假设每一个输入肯定只有一个结果。

import java.util.HashMap;

public class TwoSum {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int arr[]= {2,6,7,4,3};
		int target=9;
		HashMap map=new HashMap();
		for(int i=0;i<arr.length;i++) {
			map.put(arr[i], i);
		}
		for(int i=0;i<arr.length;i++) {
			int m=arr[i];
			int c=target-m;
			if(map.containsKey(c)) {
				if(i>(int)map.get(c)) {
					System.out.println(c+"=="+m);
				}
					
				
			}
			
		}

	}

}



posted @ 2017-09-12 10:11  清澈见底  阅读(122)  评论(0编辑  收藏  举报