zoukankan      html  css  js  c++  java
  • 2Sum

    2Sum

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target,
    where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    bool compare(const pair<int, int> &a, const pair<int, int> &b) {
        return a.first < b.first;
    }
    
    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            return twoSum_2(numbers, target);
        }
        
        // solution 1: sort and select O(nlgn)
        vector<int> twoSum_1(vector<int> &numbers, int target) { // pair<val,index>
            vector<pair<int, int> > nums(numbers.size());
            for (int i = 0; i < numbers.size(); ++i)
                nums[i] = make_pair(numbers[i], i+1);
            sort(nums.begin(), nums.end(), compare);
            
            int l = 0, r = nums.size() - 1;
            while (l < r) {
                int sum = nums[l].first + nums[r].first;
                if (sum == target) break;
                else if (sum < target) l++;
                else r--;
            }
    
            vector<int> res;
            res.push_back(min(nums[l].second, nums[r].second));
            res.push_back(max(nums[l].second, nums[r].second));
            return res;
        }
        
        // solution 2: hashtable O(n)
        vector<int> twoSum_2(vector<int> &numbers, int target) { // exist bug; hash-table
            unordered_map<int, int> map;
            for (int i = 0; i < numbers.size(); ++i)
                map[numbers[i]] = i + 1;
            for (int i = 0; i < numbers.size(); ++i) {
                unordered_map<int, int>::iterator it = map.find(target - numbers[i]);
                if (it == map.end() || i+1 == it->second) continue;
                vector<int> res;
                res.push_back(min(i+1, it->second));
                res.push_back(max(i+1, it->second));
                return res;
            }
        }
    };
  • 相关阅读:
    获得客户端的信息
    JavaScript--垃圾回收器
    JavaScript--函数-按值传递
    JavaScript--声明提前
    JavaScript--函数-01
    JavaScript--赋值表达式(typeof-delete-void)
    JavaScript—赋值表达式-1
    JavaScript--机选双色球
    正则表达式的预判
    自定义比较器函数
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3595483.html
Copyright © 2011-2022 走看看