第一题——Two Sum

2016-09-27  本文已影响0人  M1chaelY0ung

Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15],
target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

这道题要求返回两个数值i和j,使num[i]+num[j]=target;

这道题一开始的想法就是两个for循环,即
public class Solution{
    public int[] twoSum(int[] nums,int target){
        int[] back = new int[2];
        for(int i =0;i<nums.length-1;i++){
            for(int j=i+1;j<nums.length;j++){
                if(nums[i]+nums[j]==target){
                    back[0]=i;
                    back[1]=j;
                    return back;
                }
            }
        }
        return null;
    }
}
然后在网上看到了另一种时间复杂度更低的算法,贴上来也看一下:
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] back = new int[2];
        Map map = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            map.put(nums[i], i);
        }
        for(int i=0;i<nums.length;i++){
            int delNum = target-nums[i];
            if(map.get(delNum)!=null&&(int)map.get(delNum)>i){
                back[0]=i;
                back[1]=(int)map.get(delNum);
            }
        }
        return back;
    }
}
上一篇下一篇

猜你喜欢

热点阅读