• LeetCode 1. Two Sum (C++)


    题目:

    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].

    分析:

    给定一个数组和目标值,两个数如果加和等于目标值的话,则返回他们的索引。

    最先想到的肯定是Brute Force,也就是两个for循环,遍历数组,如果num[i] + num[j] == target,则返回i,j即可。不过这样的实践复杂度是O(n^2)。

    我们可以定义一个map,遍历数组并将其添加进map中,key=num[i],value=i,也就是map[num[i]] = i,并在每一次添加前查找target-num[i]是否在map中,如果在的话就返回当前的索引和找到的value就可以的。之所以在添加前查找是为了避免如:[3, 3] target = 6这样的情况,如果先添加后查找则会返回[0, 0],与题意不符。

    程序:

    //Brute Force
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> res;
            for (int i = 0; i < nums.size()-1; i++){
                for (int j = i+1; j < nums.size(); j++){
                    if (nums[i] + nums[j] == target){
                        res.push_back(i);
                        res.push_back(j);
                        break;
                    }
                }
            }
            return res;
        }
    };
    //use unordered_map
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            unordered_map<int, int> m;
            for(int i = 0; i < nums.size(); ++i){
                auto it = m.find(target-nums[i]);
                if(it != m.end()) return {it->second,i};
                m[nums[i]] = i;
            }
            return {};
        }
    };
  • 相关阅读:
    Gym 101606 F-Flipping Coins(概率dp)
    Gym101350 J Lazy Physics Cat
    Gym 101350G
    hdu6188 Duizi and Shunzi (贪心或者dp)
    Gym101350 FMonkeying Around
    codeforce 457DIV2 C题
    codeforce 457DIV2 B题
    codeforce 461DIV2 F题
    codeforce 461DIV2 E题
    PE文件RV转FOA及FOA转RVA
  • 原文地址:https://www.cnblogs.com/silentteller/p/10687226.html
Copyright © 2020-2023  润新知