您的位置:首页 > 其它

LeetCode:Two Sum

2015-01-15 12:58 471 查看

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
Solutions:
Adding each element to the Hash table takes linear time (O(n)). I store each element in the array as the key and its position as the value. The idea is to find the key value (target - index1) if it's not null (it exists), then index2
is the value of that key. Each lookup takes constant time (O(1)) and in the worst case, it'll run n times.
import java.util.HashMap;
import java.util.Map;
public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] solution = new int[2];
        Map<Integer, Integer> H = new HashMap<Integer,Integer> (numbers.length);

        // O(n) time for adding each element to the Hash table.
        for(int i=0; i<numbers.length; i++) {
            H.put(numbers[i], i);
        }

        // Lookup for element index2 such that index2==(target-index1) (O(1)) 
        // O(1) for each lookup, O(n) total.
        for(int i=0; i<numbers.length; i++) {
            if(H.get(target-numbers[i]) != null && H.get(target-numbers[i])!=i) {
                solution[0] = i+1;
                solution[1] = H.get(target - numbers[i]) +1;
                break;
            }
            else continue;
        }
        return solution;
    }
    
    private int findIndex(int[] numbers, int num, int start){
        for(int i = start;i < numbers.length;i++)
         if(numbers[i] == num) return i;
        return -1;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: