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("]"); } }
相关文章推荐
- find two numbers such that they add up to a specific target number
- Given an array of integers, sort the array according to frequency of elements
- CareerCup Given an array of (unsorted) integers, arrange them such that a < b > c < d > e... etc.
- pointer to ref of an array, and to the func that return a ref of an array
- Given the array of digits (0 is also allowed), what is the minimal sum of two integers that are made
- Given an integer, return all sequences of numbers that sum to it
- given an array of integers Find the index of values that satisfy A+B = C + D
- Given an array of ages (integers) sorted lowest to highest, output the number of occurrences for eac
- Given a non-empty array of integers, return the k most frequent elements.
- Given an array nums, write a function to move all 0's to the end of it while maintaining the relativ
- Given an array of integers, every element appears twice except for one. Find that single one.
- Given an array t[100] which contains numbers between 1..99. Return the duplicated value
- Data Structure Array: Given an array arr[], find the maximum j – i such that arr[j] > arr[i]
- You’re given an array containing both positive and negative integers and required to find the sub-a
- Given an array of size n, find the majority element. The majority element is the element that appear
- Given an array of numbers, return array of products of all other numbers (no division)
- Given an array of integers, every element appears twice except for one. Find that single one.
- Given an array of positive and negative integers find the first subarray with zero sum
- Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree andsum =
- Given an array of integers, every element appears twice except for one. Find that single one.