LeetCode-1.Two Sum

    xiaoxiao2021-03-26  25

    1.题目描述

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

    2.我的分析思路

    首先,最直接的思路就是遍历数组,分两次遍历,找到结果后直接返回即可。直接上代码:

    public static int[] twoSum(int[] nums, int target) throws IllegalArgumentException { for (int i = 0; i < nums.length; 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 num found"); }

    这个算法的时间复杂度为

    O(n^2)

    空间复杂度为:

    O(1)

    3.其他的思路

    3.1 思路1

    将所有数组内的下标和值存储到一个map中,然后只需要遍历一次数组,每个数据进行计算,算出对应的差值,如果这个差值在map中存在,那么就直接返回两个下标,否则抛出异常。

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

    分析这个算法,可以得到,这个算法的时间复杂度为:

    O(n)

    空间复杂度为:

    O(n)

    是典型的空间换时间的算法。

    思路2

    还是空间换时间的思路,直接遍历数组,计算差值,如果在map中存在这个值,直接返回,否则将数组中的值存入map中。

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

    分析这个算法,可以得到,这个算法的时间复杂度为:

    O(n)

    空间复杂度为:

    O(n)

    是典型的空间换时间的算法。

    转载请注明原文地址: https://ju.6miu.com/read-664271.html

    最新回复(0)