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;
        }
    };
    
  • 相关阅读:
    html5 canvas 像素随机百分之十显示
    html5 canvas防微博旋转
    html5 canvas 旋转扩大
    html5 canvas 钟表
    html5 canvas 移动小方块
    html5 canvas 鼠标绘制
    html5 拖放到购物车
    html5 拖拽
    js_sl 无缝切换
    HDU 2048 神、上帝以及老天爷( 错排 )
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6749948.html
Copyright © 2011-2022 走看看