第一周。
1,two sum。
Two Sum Description Notes Testcase Judge 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. Notice You may assume that each input would have exactly one solution Have you met this question in a real interview? Yes Example numbers=[2, 7, 11, 15], target=9 return [1, 2]
答案和解析:利用List来存前面出现过的元素,然后通过查找是否出现了target - 当前值的元素。来判断是否有组合对。
public class Solution { /* * @param numbers : An array of Integer * @param target : target = numbers[index1] + numbers[index2] * @return : [index1 + 1, index2 + 1] (index1 < index2) */ public int[] twoSum(int[] numbers, int target) { // write your code here ArrayList<Integer> list = new ArrayList(); int[] res = new int[2]; for (int i = 0; i < numbers.length; ++i) { if (list.contains(target - numbers[i])) { res[0] = list.indexOf(target - numbers[i]) + 1; res[1] = i + 1; break; } else { list.add(numbers[i]); } } return res; } }
原文:http://www.cnblogs.com/yueyebigdata/p/5510888.html