题目描述:
给出一个整数数组,请在数组中找出两个加起来等于目标值的数, 你给出的函数twoSum 需要返回这两个数字的下标(index1,index2),需要满足 index1 小于index2.。注意:下标是从1开始的 假设给出的数组中只存在唯一解 例如:给出的数组为 {20, 70, 110, 150},目标值为90
输出 index1=1, index2=2
import java.util.*; public class Solution { /** * * @param numbers int整型一维数组 * @param target int整型 * @return int整型一维数组 */ public int[] twoSum (int[] numbers, int target) { // write code here int[] result = {-1,-1}; int len = numbers.length; for (int i=0; i<len;i++){ System.out.println("i_numbers:"+i); for (int j=0;j<len;j++){ System.out.println("j_numbers:"+j); if (numbers[i] + numbers[j] == target && i<j){ // System.out.println("i_numbers:"+numbers[i] + ",j_numbers:"+numbers[j]); result[0] = i+1; result[1] = j+1; } } } // System.out.println(Arrays.toString(result)); return result; } }
2
import java.util.*; public class Solution { public int[] twoSum(int[] numbers, int target) { int[] res = new int[]{-1,-1}; HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < numbers.length; i++) { map.put(numbers[i] , i); } for (int i = 0; i < numbers.length; i++) { int two = target - numbers[i]; if (map.containsKey(two) && target != 2*two){ res[0] = i < map.get(two) ? i + 1 : map.get(two) + 1 ; res[1] = i > map.get(two) ? i + 1 : map.get(two) + 1; } } return res; } }