【LeetCode】Two Sum 解题报告

来源:互联网 发布:决战武林雨扇进阶数据 编辑:程序博客网 时间:2024/05/16 03:50

【LeetCode】Two Sum 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/two-sum/#/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.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

Ways

这个题首先想到的是时间复杂度O(n^2)的遍历,但是肯顶会超时,所以想到用HashMap保存已经有的数据出现的额位置,这样可以使如果要求的数字出现的时候不再继续遍历,及时停止即可。有个技巧就是判断差是否在HashMap中,而不是遍历一遍HashMap来求和。

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

Date

2017 年 5 月 18 日