leetcode1:在数组中找2个数的和正好等于一个给定值--哈希

package java_net_test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class twoSum {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int target=9;
  int[] num={2,7,11,15};
  int[]res;
 
  for(int i=0;i<2;i++){
 
   System.out.println(twoSum(num,target)[i]);
  }
 }
 public static int[] twoSum(int[] numbers, int target) {
   int[] res = new int[2];
   Map<Integer,Integer> table = new HashMap<Integer,Integer>();
   for(int i = 0; i < numbers.length; i++){
   table.put(numbers[i], i);
   }
   for(int i = 0; i < numbers.length; i++){
    int tem = target - numbers[i];
    if(table.get(tem)!= null&&table.get(tem)!=i){//table.get(tem)找第二个数
     res[0] = i+1;
     res[1] = table.get(tem) + 1;
     break;
    }
   }
   return res;
       }
 
 }
posted @ 2015-08-07 12:00  lily园  Views(217)  Comments(0Edit  收藏  举报