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

    从一个vector里找到两个数的和为target(这两个数唯一),返回index

    很快地写出一个(O(n^2))的版本,可以稍微优化下,用二分查下有没有target-nums.at(i)再for循环去找index
    (二分查找由于要先排序,所以无法返回index,只能判断有没有)

        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> result;
            for (int i = 0; i < nums.size(); i++)
            {
                int rest = target - nums.at(i);
    
                for (int j = 0; j < nums.size() && j != i; j++)
                {
                    if (nums.at(j) == rest)
                    {
                        result.push_back(i);
                        result.push_back(j);
                        break;
                    }
                }
            }
    
            return result;
    

    这种版本显然不能令人满意,使用map写出一个更快的版本

    vector [2, 7, 11, 15]
    map { {2, 0}, {7, 1}, {11, 2}, {15, 3} }

    map的key存vector的value, map的value存vector的index
    这样可以快速查到target - nums.at(i)是否存在以及index

    题目里说明了这两个数唯一,所以当遇到 [3, 2, 3]这种有重复元素的vector时,target只能为6,for循环到第二个3时,程序就返回了,没有把第二个3的index存到map中去,所以用map也不会出现问题

    vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> result;
            map<int, int> num_map;
    
            for (int i = 0; i < nums.size(); i++)
            {
                int rest = target - nums.at(i);
                if (num_map.find(rest) != num_map.end()) //map中存在该元素
                {
                    result.push_back(i);
                    result.push_back(num_map[rest]);
                }
                else
                {
                    num_map[nums.at(i)] = i;
                }
            }
    
            return result;
        }
    

    LeetCode上其他人的做法也是用的map,就不介绍了

  • 相关阅读:
    Loadrunner 9.5_webservice(SOAP)性能测试
    oracle分层查询中的start with和connect by(树结构查询)
    解析Nginx负载均衡
    Nginx+tomcat配置集群负载均衡
    基于Nginx反向代理及负载均衡
    什么是反向代理,如何区别反向与正向代理
    软件测试策略
    软件测试策略的制定过程
    php 模拟get和post提交方法[解决ajax跨域问题]
    解决ajax跨域问题的多种方法
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9365603.html
Copyright © 2011-2022 走看看