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].

 

Navie solution:

思路: 返回是一个array,所以需要新建一个res array来return。

和为target,思路是两次遍历数组,使用快慢指针,和为target则直接把指针的数值赋给res,然后跳出循环。返回res array。

Time Complexity: O(n^2)

 

public class Solution {

    public int[] twoSum(int[] nums, int target) {

        int[] res=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)

                {

                    res[0]=i;

                    res[1]=j;

                }

            }

        }

        return res;

    }

}

注意事项:

一定要写corner case

比如nums.length==0 但是这道题已经说了必然有两个solution,所以不用也可。

 

Solution 2:

思路: 目的是想要优化算法,变成O(n)

用hashmap 数据结构,遍历数组的时候如果hashmap里面没有这个数就把target-nums[i]存进去。这个非常巧妙,存入减后的值代表我这个hashmap有之前的值,如果之后有另一个值搭配之前的值使和为target,则为解。

    public int[] twoSum(int[] nums, int target) {

        int[] res=new int[2];

        Map<Integer,Integer> check=new HashMap<Integer,Integer>();

        for(int i=0;i<nums.length;i++)

        {

            if(!check.containsKey(nums[i]))

            {

            check.put(target-nums[i],i);

            }

            else

            {

                res[0]=i;

                res[1]=check.get(nums[i]);

                break;

            }

        }

        return res;

    }

 

注意事项: set 是contains

hashmap是containsKey, containsValue

 

posted on 2016-09-09 13:17  Machelsky  阅读(120)  评论(0)    收藏  举报