zoukankan      html  css  js  c++  java
  • Leetcode: 1.Two Sum

    Description

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

    思路

    • 直接一个排序,O(nlgn),然后一个查找,O(n)
    • 使用unordered_map<int,int>可直接实现O(n)的解法

    代码

    • O(nlgn)的解法
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> res;
            int len = nums.size();
            if(len == 0) return res;
            
            vector<pair<int, int>> vec;
            for(int i = 0; i < len; ++i){
                vec.push_back(pair<int, int>(nums[i], i));
            }
            
            sort(vec.begin(), vec.end(), 
                [](const pair<int, int> &a, const pair<int, int>&b){ return a.first < b.first;});
                
            int i = 0, j = len - 1, tmp;
            while(i < j){
                tmp = vec[i].first + vec[j].first;
                if(tmp == target){
                    res.push_back(min(vec[i].second, vec[j].second));
                    res.push_back(max(vec[i].second, vec[j].second));
                    break;
                }
                else if(tmp < target)
                    i++;
                else j--;
            }
            
            return res;
        }
    };
    
    • O(n)的解法
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> res;
            int len = nums.size();
            if(len == 0) return res;
            
            unordered_map<int, int> hash;
            int needToFind = 0;
            for(int i = 0; i < len; ++i){
                needToFind = target - nums[i];
                if(hash.find(needToFind) != hash.end()){
                    res.push_back(min(i, hash[needToFind]));
                    res.push_back(max(i, hash[needToFind]));
                    break;
                }
                else{
                    hash.insert(pair<int, int>(nums[i], i));
                }
            }
            return res;
        }
    };
    
  • 相关阅读:
    更好的处理 Python 多工程 import 依赖
    Django 前后台的数据传递
    Django传递数据给JS
    nodejs 设置跨域访问
    Node.js + Express
    前端用户输入校验--基于JQ
    git统计当前分支提交次数
    gitlab相关
    CentOS7使用firewalld打开关闭防火墙与端口
    puppeteer安装/爬取数据
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6749948.html
Copyright © 2011-2022 走看看