Leetcode 1. Two Sum

来源:互联网 发布:贵州6频道网络电视 编辑:程序博客网 时间:2024/05/16 18:06

Leetcode 1. 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, 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),后来我想到使用Map来加速查询效率,优化到O(n),

这道题给我的最大的启发就是在大量的遍历查询的出现下,可以使用Set或者Map等关联容器来加速查询效率,这是典型的空间换时间。

代码如下:

import java.util.HashMap;import java.util.Map;public class Solution {    /*     * 使用Map加速查找效率     * */     public int[] twoSum(int[] nums, int target)      {            int []res={0,0};            Map<Integer, Integer> map=new HashMap<Integer, Integer>();            for(int i=0;i<nums.length;i++)                map.put(nums[i], i);            for(int i=0;i<nums.length;i++)            {                int index=map.getOrDefault(target-nums[i], -1);                if(index>=0 && index!=i)                {                    res[0]=i;                    res[1]=index;                    break;                }            }            return res;     }    /*     * 遍历求解     * */    public int[] twoSum111(int[] nums, int target)     {        int []res={0,0};        boolean find=false;        for(int i=0;i<nums.length;i++)        {            int a=nums[i];            int b=target-a;            for(int j=1+i;j<nums.length;j++)            {                if(nums[j]==b)                {                    find=true;                    res[1]=j;                    break;                }            }            if(find)            {                res[0]=i;                break;            }        }        return res;    }}

下面是C++答案

#include <iostream>#include <vector>#include <map>using namespace std;//注意使用Map等数据结构class Solution{public:    vector<int> twoSum(vector<int>& nums, int target)    {        vector<int> res;        map<int,int> myMap;        for(int i=0;i<nums.size();i++)            myMap[nums[i]]=i;        for(int i=0;i<nums.size();i++)        {            int one=target-nums[i];            map<int,int>::iterator iter = myMap.find(one);            if(iter!= myMap.end() && iter->second != i)            {                res.push_back(i);                res.push_back(iter->second);                break;            }        }        return res;    }};
原创粉丝点击