Wednesday, December 28, 2016

Leetcode/各大家 -- 1. Two Sum(HashMap)


1. Two Sum(HashMap)
  • Difficulty: Easy
https://leetcode.com/problems/two-sum/
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].

思路:loop用Hashmap存入数组<val,index>,每次查是否当前target - element值存在于Hashmap中。
关键字:HashMap

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        int[] res = new int[2];
        for(int i=0;i<nums.length;i++){
            int val = target - nums[i];
            if(map.containsKey(val)){
                res[0]=map.get(val);
                res[1]=i;
                return res;
            }else{
                map.put(nums[i],i);
            }
        }
        
        return res;
    }
}

No comments:

Post a Comment