关闭

Two Sum

188人阅读 评论(0) 收藏 举报
分类:
题目: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;  
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:68356次
    • 积分:3667
    • 等级:
    • 排名:第8839名
    • 原创:312篇
    • 转载:3篇
    • 译文:0篇
    • 评论:3条
    文章分类
    最新评论