美文网首页
LeetCode001-Two Sum

LeetCode001-Two Sum

作者: Kay_Coding | 来源:发表于2018-11-17 10:58 被阅读0次

Two Sum

Question:

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

解法代码

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class LeetCode001 {

    public static void main(String[] args) {
        int[] iArray = new int[]{2,5,6,3,7,2,9};
        int target = 5;
        
        System.out.println(Arrays.toString(
                new LeetCode001().twoSumForce(iArray, target)));
        System.out.println(Arrays.toString(
                new LeetCode001().twoSum(iArray, target)));
    }
    //暴力法
    //遍历每个元素x,并查找是否存在值等于target - x的目标值
    public int[] twoSumForce(int[] nums, int target) {
        for(int i = 0; i < nums.length - 1; i++) {
            for(int j = i+1; j < nums.length; j++) {
                if(nums[j] == target - nums[i]) {
                    return new int[]{i, j};
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution!");
    }
    
    //一遍哈希遍历法,运用空间换时间
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(map.containsKey(target - nums[i])) {//哈希表查找时间复杂度O(1)
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution!");
    }

}

Output:

[0, 3]
[0, 3]

Time And Space Complexity

  • twoSumForce

Time: O(n^2) 两次循环遍历查找O(n)*O(n)
Space:O(1)

  • twoSum

Time: O(n) 只遍历了一次有n个元素的列表O(n),在哈希表查找数据的时间复杂度为O(1)
Space:O(n) 新增了哈希表

Tips

哈希表可以将查找时间从 O(n) 降低到O(1),哈希表正是为此目的而构建的,它支持以近似恒定的时间进行快速查找。我用“近似”来描述,是因为一旦出现冲突,查找用时可能会退化到O(n)。但只要你仔细地挑选哈希函数,在哈希表中进行查找的用时应当被摊销为O(1)

相关文章

网友评论

      本文标题:LeetCode001-Two Sum

      本文链接:https://www.haomeiwen.com/subject/lbsbfqtx.html