标签:
import java.util.HashMap; public class TwoSum { public static void main(String[] args) { int[] input = { 2, 7, 11, 2 }; int target = 4; int[] result = TwoSum2(input, target); for (int i = 0; i < result.length; i++) { System.out.println(result[i]); } } // 如果input数组是升序 public static int[] TwoSum1(int[] input, int target) { int[] result = new int[2]; int index1 = 0; int index2 = result.length; for (int i = 0; i < result.length; i++) { if (input[index1] + input[index2] == target) { result[0] = index1 + 1; result[1] = index2 + 1; } else if (input[index1] + input[index2] < target) { index1++; } else { index2--; } } return result; } // 如果input数组是无序,map中key保存需要的数值,value保存索引 public static int[] TwoSum2(int[] input, int target) { int[] result = new int[2]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < input.length; i++) { if (map.containsKey(input[i])) { result[0] = map.get(input[i]) + 1;//map的value保存另一个索引 result[1] = i + 1;//当前i记录当前的索引 } else { map.put(target - input[i], i); } } return result; } }
标签:
原文地址:http://www.cnblogs.com/libeiucas/p/4936982.html