TwoSum
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
http://oj.leetcode.com/problems/two-sum/
思路:
直接暴力搜索O(N^2)
1、如果没有负数,hash最快
2、先排序,可以将时间复杂度见到O(nlogn),只要保存到set中,就可以快速查找
code
public static int[] twoSum(int[] numbers, int target) { int[] indice = new int[2]; Set<Integer> set = new HashSet<>(); for (int i : numbers) set.add(i); for (int i=0; i<numbers.length; i++) { if (set.contains(target - numbers[i])) { for (int j=i+1; j<numbers.length; j++) { if (numbers[i] + numbers[j] == target) { indice[0] = i+1; indice[1] = j+1; return indice; } } } } return indice; }