【LeetCode】1. Two Sum 解题报告

来源:互联网 发布:淘宝商家提供发票不符 编辑:程序博客网 时间:2024/05/22 12:08

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51471280


Subject

出处:https://leetcode.com/problems/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.

Example:

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

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


Explain

该题目给定一个int型数组,和一个target数值。要求找出数组中两个下标对应的数字之和等于target。

返回两个下标组成的数组。


Solution

solution 1

最笨的方法就是循环嵌套。

public static int[] twoSum(int[] nums, int target) {        int[] result = new int[2];        if (nums == null || nums.length == 0) {            return result;        }        for (int i = 0; i < nums.length; i++) {            for (int j = i + 1; j < nums.length; j++) {                if (nums[i] + nums[j] == target) {                    result[0] = i;                    result[1] = j;                    return result;                }            }        }        return result;    }

该方法时间复杂度较高,O(n²)。
空间复杂度是O(1)。


solution 2

虽然方法一通过了测试,但是时间复杂度较高。
然后看到该题目的提示标签是【Array】【Hash Table】,就想到使用HashMap来存储下标和值。

/**     * 使用HashMap存储 <br />     *      * @param nums     * @param target     * @return     */    public static int[] twoSum2(int[] nums, int target) {        int[] result = new int[2];        HashMap<Integer, Integer> map = new HashMap<>();        for (int i = 0; i < nums.length; i++) {            if (map.containsKey(target - nums[i])) {                if (i > map.get(target - nums[i])) {                    result[0] = map.get(target - nums[i]);                    result[1] = i;                } else {                    result[0] = i;                    result[1] = map.get(target - nums[i]);                }            } else {                map.put(nums[i], i);            }        }        return result;    }

注意将 nums[i] 作为key,将下标 i 作为value。
判断map里面是否存在 target-nums[i] 这个key。


bingo~~

1 0
原创粉丝点击