1. Two Sum

Description:

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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


Solution:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> 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 left = target - nums[i];
            if(map.containsKey(left) && map.get(left) != i){
                return new int[]{i,map.get(left)};
            }    
        }
        return null;
    }
}

理解:

利用HashMap的特性,时间复杂度:O(N);空间复杂度:O(N)

left表示Target-nums[i],再判断left是否在map中存在,并且left下标和i不相同,则存在并且返回下标值,否则返回null。

 

 

 


posted @ 2019-04-11 09:33  SnailsCoffee  阅读(76)  评论(0)    收藏  举报