Two Sum
题目: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



如果使用暴力搜索,时间复杂度为O(n*n)

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] temp=new int[2];
        for(int i=0;i<nums.length;i++){
            for(int j=i+1;j<nums.length;j++){
                if(nums[i]+nums[j]==target){
                    temp[0]=i+1;
                    temp[1]=j+1;
                }
            }
        }
        return temp;
    }
}

解法:利用HashMap,存储数组中的值和Index,使用get方法,get到target-nums[i],

记录当前的index,否则将nums[i] put到HashMap中。时间复杂度只有O(n)。

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //记录值和index
        int[] ret = new int[2]; //辅助数组
        for(int i=0; i<nums.length; i++){  
            if(map.get(target-nums[i]) != null){  //找到值对应的index
                ret[0] = map.get(target-nums[i]) + 1;  
                ret[1] = i+1;  
            }else 
                map.put(nums[i], i);//没有找到则记录
        }  
        return ret;  
    }
}


阅读更多
个人分类: LeetCode java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Two Sum

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭