zoukankan      html  css  js  c++  java
  • leetcode1 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].

    UPDATE (2016/2/13):

    The return format had been changed to zero-based indices. Please read the above updated description carefully.

    题意:找出一个数组中两个数和为target的下标。

    原始做法:双重循环,简单无脑,就是慢了点。

    代码

    vector<int> twoSum(vector<int>& nums, int target)
    {
        vector<int> ans;
        int l = nums.size(),j,k;
    
        for(j=0;j<l-1;j++)
        {
            for(k=j+1;k<l;k++)
            {
                if(nums[j] + nums[k] == target)
                {
                    ans.push_back(j);
                    ans.push_back(k);
                    break;
                }
            }
        }
        return ans;
    }

    优化做法:上面做法的时间复杂度O(n2),而使用map(unordered_map)来存储之前查询过的数据,可以达到O(n)的复杂度。
    代码:
    vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> ans;
            map<int, int> m;
            for(int i=0;i<nums.size();i++)
            {
                if(m.find(target-nums[i]) != m.end())
                {
                    ans.push_back(m[target-nums[i]]);
                    ans.push_back(i);
                    break;
                }
                m[nums[i]] = i;
            }
            return ans;
        }

    这里用map或者unordered_map都可以过,区别是map会比unordered_map慢一点。

    查了资料,map对应的是JAVA中的TreeMap,而unordered_map对应HashMap,具体区别在以后的博客中继续讨论。



  • 相关阅读:
    html5--html实现乘法口诀表
    html5--switch选择结构的优化
    CSS盒子模型
    html5--项目实战-仿天猫(移动端页面)
    关于运动
    自然拼读法长元音
    揭开自然拼读法(Phonics)的神秘面纱
    ExtJs自学教程(1):一切从API開始
    四个好看的CSS样式表格
    【Linux】linux经常使用基本命令
  • 原文地址:https://www.cnblogs.com/puyangsky/p/5261563.html
Copyright © 2011-2022 走看看