LeetCode--Array--Two sum (Easy)

1.Two sum (Easy)

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

题意是给定一个int数组nums和一个整数target,在nums里面找到两数之和为target的数,并返回两数的数组索引。假定nums数组里面只有惟一的一组结果,且同一个数字只能使用一次。算法

1.最容易想到的暴力算法,也就是我起初想到的!!!数组

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] indices = new int[2];
        for (int i = 0; i < nums.length - 1; i++)
        {
            for (int j = i + 1; j < nums.length; j++)
            {
                if (nums[i] + nums[j] == target)
                {
                    indices[0] = i;
                    indices[1] = j;
                    return indices;
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

2.速度更快的解法,HashMapspa

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> m = new HashMap<Integer,Integer>();
        for (int i = 0; i < nums.length; i++)
        {
            int complement = target - nums[i];
            if (m.containsKey(complement))
                return new int[] {m.get(complement),i};
            m.put(nums[i],i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

reference
https://leetcode.com/articles/two-sum/code

总结

第一种暴力算法就是先取一个数,而后用这个数依次与后面的每个数相加求和,若和与target相等,则将这两个数的数组索引加入到一个新的int数组中,而后返回这个int数组。time complexity:O(n^2),space complexity:O(1)索引


第二种使用HashMap的方法起初不太容易想到。基本思路是将数组值做为键,索引做为值。是先建立一个hashmap,而后遍历数组nums,若是hashmap中已经存在complement=target-nums[i]这个元素,则将complement键对应的值(即数组索引),和i存到一个新的int数组里面并返回;若果不存在,则将nums[i],i分别做为键与值存到hashmap中去。若是遍历完数组没有找到相应的结果,则抛出异常。time complexity:O(n),space complexity:O(n)ci


Notes
1.数组值和下标互换是一种经常使用的技巧,不过只对整数有用;element

相关文章
相关标签/搜索