LeetCode-1. Two-sum

来源:互联网 发布:java中方法重载的作用 编辑:程序博客网 时间:2024/06/09 18:26

题目概述:

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

方法一(自己想到的):

暴力搜索:首先假设确定一个数,这样就需要在数组中寻找数值等于(目标数-假设确定的数)的这么一个数,如果存在则记录下标并返回,如果全都遍历完都没有找到,则返回空的数组,时间复杂度O(n^2)。

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        int num=nums.size();        vector<int> res;        for(int i=0;i<num;++i)        {            int myTarget=target-nums[i];            for(int j=i+1;j<num;++j)            {                if(nums[j]==myTarget)                {                    res.push_back(i);                    res.push_back(j);                    return res;                }            }        }        return res;    }};

方法二:

使用hash表:时间复杂度:O(n),空间复杂度:O(n)。遍历一次数组,将数都放在hash表中,再遍历一次数组并在表中寻找第二个数。

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


更详细的解答请参考:https://leetcode.com/problems/two-sum/solution/

原创粉丝点击