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

Approch 1: Brute Force 暴风算法

Time complexity : O(n2).

Space complexity : O(1)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i=0; i<nums.length; i++){
            for(int j=i+1; j<nums.length;j++){ 
                if((nums[i] + nums[j]) == target) {
                    return new int[]{i,j}; //注意这个return新数组的格式!
                }
            }
        }
      //注意最后没有return的话补加一个异常声明
throw new IllegalArgumentException("No two sum solution"); } }

Approch 2:Two-pass Hash Table

Time complexity : O(n).

Space complexity : O(n).

!!第一次用Map和HashMap(都属于java.util, 实际用的时候需要导入)

标记c为带查找的那个差值,然后用哈希表就能很快get该值对应的在数组中的序号。因此只需要一个for循环就够了。

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 c = target - nums[i];
            if(map.containsKey(c)&&map.get(c)!=i){
                return new int[]{i,map.get(c)};
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

 

posted @ 2019-01-18 20:32  JamieLiu  阅读(142)  评论(0编辑  收藏  举报