• leetcode_1: two sum


    暴力

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            int i, j;
            for (i = 0; i < nums.size(); ++i){
                for(j = i + 1; j < nums.size(); ++j) {
                    if(nums[i] + nums[j] == target) {
                        return {i, j};
                    }
                }
            }
            return {i, j};
        }
    };
    

    两遍hash

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            map<int, int> m;
            vector<int> b(2, -1);
            for(int i = 0; i < nums.size(); ++i){
                m.insert(map<int, int>::value_type(nums[i], i));
            }
            for(int i = 0; i < nums.size(); ++i){
                if(m.count(target - nums[i]) > 0 && m[target - nums[i]] != i){
                    b[0] = i;
                    b[1] = m[target - nums[i]];
                    break;
                }
            }
            return b;
        }
    };
    

    一遍hash

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            map<int, int> m;
            vector<int> b(2, -1);
    
            for(int i = 0; i < nums.size(); ++i){
                if(m.count(target - nums[i]) > 0){
                    b[0] = i;
                    b[1] = m[target - nums[i]];
                    break;
                }
                m[nums[i]] = i;
            }
            return b;
        }
    };
    
  • 相关阅读:
    Python之图片格式转换
    pip依赖安装与记录
    Spectral Graph Theory的一些定理
    Beamer加中文
    Python之json
    Windows之建立C++开发环境
    Mysql分表教程
    null和空 not null
    yii 隐藏index.php的步骤
    yii泛域名
  • 原文地址:https://www.cnblogs.com/fengcnblogs/p/13705327.html
Copyright © 2020-2023  润新知