• [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;
    }
  • 相关阅读:
    JavaScript中DOM的层次节点(一)
    JS可维护性代码
    Angular页面加载闪现解决方案 ng-cloak
    无法向会话状态服务器发出会话状态请求。
    算法题--拓扑排序
    2020年04月25日个人赛
    Educational Codeforces Round 86 (Rated for Div. 2)
    博弈--巴什博弈
    2020年04月19日个人赛
    AtCoder Beginner Contest 163(D)
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6431329.html
Copyright © 2020-2023  润新知