[LeetCode java] 1.Two Sum

来源:互联网 发布:苹果mac输入法 编辑:程序博客网 时间:2024/06/05 04:20
import java.util.Arrays;import java.util.HashMap;/** * problem number:1 * problem name: Two Sum *  * problem description: *  * 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 *  * */public class TwoSum {//16 / 16 test cases passed.//Status: Accepted//Runtime: 235 ms//Submitted: 0 minutes agopublic int[] twoSum(int[] numbers, int target) {HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();for (int i = 0; i < numbers.length; i++) {if (m.get(numbers[i]) != null) {return new int[] {m.get(numbers[i]) + 1, i + 1};}m.put(target - numbers[i], i);}throw new RuntimeException();}public static void main(String[] args) {int[] numbers = new int[]{2, 7, 11, 15};int[] results = new TwoSum().twoSum(numbers, 9);System.out.println(Arrays.toString(results));}}

0 0