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<int> twoSum(vector<int>& nums, int target)
        {
            if (nums.size() == 0) return nums;
            vector<int>result;
            //sort(nums.begin(), nums.end());
            for (int i = 0; i < nums.size(); i++)
            {
                for (int j = i + 1; j < nums.size();j++)
                {
                    if (nums[i]+nums[j] == target)
                    {
                        result.push_back(i);
                        result.push_back(j);
                        return result;
                    }
                }
            }
            return result;
        }

    然后看到大牛的代码:只需遍历一次数组,时间复杂度为O(n).

    vector<int> twoSum(vector<int> &numbers, int target)
    {
        //Key is the number and value is its index in the vector.
        unordered_map<int, int> hash;
        vector<int> result;
        for (int i = 0; i < numbers.size(); i++) {
            int numberToFind = target - numbers[i];
    
                //if numberToFind is found in map, return them
            if (hash.find(numberToFind) != hash.end()) {
                        //+1 because indices are NOT zero based
                result.push_back(hash[numberToFind] + 1);
                result.push_back(i + 1);            
                return result;
            }
    
                //number was not found. Put it in the map.
            hash[numbers[i]] = i;
        }
        return result;
    }
  • 相关阅读:
    CommandLine
    eclipse创建java和web工程
    rabbitmq安装(ubuntu)
    vue搭建手顺
    docker配置仓库源
    spark基本概念整理
    Vue整合d3.v5.js制作--柱状图(rect)
    Vue整合d3.v5.js制作--折线图(line)
    k8s强制删除pod
    踩坑ios H5
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6431329.html
Copyright © 2011-2022 走看看