1. Two Sum

作者: CNSumi | 来源:发表于2017-04-21 18:05 被阅读0次

Description:

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.
有一个整型数组和一个目标值,返回可以两个相加的和为目标值的下标。
每个输入有且仅有一个正确的输出,每个元素只能使用一次。

Samples:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solutions

<ol>
<li>O(n^2)的解决方案

public 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 new int[] {1, 1};
    }
}

因为在题目中假设每个用例有且仅有一个解,所以下面的return new int[] {1, 1};不会被执行到。这种解法的时间复杂度为大O平方阶,不需要额外的空间。</li>
<li>O(n)的解决方案

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                result[0] = map.get(target - nums[i]);
                result[1] = i;
                return result;
            }
            map.put(nums[i], i);
        }
        return result;
    }
}

这种方法将每次遍历的数值存储在map中,以值为key,以位置为值,这样在下次需要这个值时从map中取出返回。</li>
</ol>

TestCase

<ol>
<li>[[10,2,3,1,7], 10]</li>
<li>[]

相关文章

  • LeetCode 1. Two Sum (Easy)

    LeetCode 1. Two Sum (Easy) LeetCode 1. Two Sum (Easy) 原题链...

  • 1. Two Sum

    1. Two Sum 题目:https://leetcode.com/problems/two-sum/ 难度: ...

  • leetcode hot100

    1. Two Sum[https://leetcode-cn.com/problems/two-sum/] 字典(...

  • leetCode #1

    #1. Two Sum

  • 1. Two Sum

  • 1. Two Sum

    Given an array of integers, return indices of the two num...

  • 1. Two Sum

    Description Given an array of integers, return indices of...

  • 1. Two Sum

    Problem Given an array of integers, return indices of the...

  • 1. Two Sum

    Given an array of integers, return indices of the two num...

  • 1. Two Sum

    Leetcode: 1. Two SumGiven an array of integers, return in...

网友评论

    本文标题:1. Two Sum

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