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

Solution: 暴力遍历 时间复杂度是O(n2); 使用Hashmap, 时间复杂度O(n)

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        int key;
        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>(); //constructor of hashmap
        for(int i = 0; i < nums.length; i++){ //traverse array
            hashMap.put(nums[i], i); //insert hashmap
        }
        
        for(int i = 0; i < nums.length; i++){
            key = target-nums[i];
            if(hashMap.containsKey(key)
              && hashMap.get(key)!=i){//cannot be itself
                result[0] = i;
                result[1] = hashMap.get(key); //hashmap get value
                break;
            }
        }
        return result;
    }
}

 

posted on 2016-04-30 07:38  joannae  阅读(156)  评论(0编辑  收藏  举报

导航