Two Sum

来源:互联网 发布:单片机应用技术 编辑:程序博客网 时间:2024/05/01 06:19

Question:

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


//********** Hints ************

如果是排好序的数组,可以用两个指针,一个在头一个在尾向中间求和;

像此题没排好序的数组,用HashMaP达到O(n)的时间复杂度。

//*****************************


Solution:

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
       HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();  
        int n = numbers.length;  
        int[] result = new int[2];  
        for (int i = 0; i < numbers.length; i++)  
        {  
            if (map.containsKey(target - numbers[i]))  
            {  
                result[0] = map.get(target-numbers[i]) + 1;  
                result[1] = i + 1;  
                break;  
            }  
            else  
            {  
                map.put(numbers[i], i);  
            }  
        }  
        return result;  
    }
}

0 0
原创粉丝点击