您的位置:首页 > 其它

Given an array of integers, return indices of the two numbers such that they add up to a specific ta

2017-04-14 21:23 791 查看
import java.util.HashMap;
import java.util.Scanner;

import javax.swing.text.NumberFormatter;

public class Solution {
public static int[] twoSum(int[] num,int target ) {
final HashMap<Integer,Integer> myMap = new HashMap<Integer, Integer>();
//int []result = new int[2];
for (int i = 0; i < num.length; i++) {
myMap.put( num[i],i);
}
for (int i = 0; i < num.length; i++) {
int v =  myMap.get( target - num[i]);
if (v != 0 && v > i) {
return new int[]{i,v};
}
}
return null;

}
public static void main(String[] args) {
int num[] = new int[]{2,7,11,15};
Scanner scanner = new Scanner(System.in);
int target = scanner.nextInt();
int []array = twoSum(num, target);
System.out.print("[");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
//System.out.print("");
}
System.out.print("]");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐