2Sum problem

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

用hashmap来做,我们用target减去每个数得到每个数需要的数字,然后把它存在hashmap的key中,value存当前数字的index。
所以每次我们只需用containsKey检测当前数字是否在key中和另一个数配对,如果配对,我们拿出index和当前数字index一起返回。

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
        
        HashMap<Integer, Integer> map = new HashMap<>();
        
        for(int i = 0; i < numbers.length; i++) {
            if (map.containsKey(numbers[i])) {
                
                int[] result = {map.get(numbers[i]) + 1, i + 1};
                return result;
            }
            
            map.put(target - numbers[i], i);
        }
        
        int[] result = {};
        return result;
        
        
    }
    
    
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容