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;
            }
        }
    };
  • 相关阅读:
    Linux系统编程——特殊进程之僵尸进程
    怎样让你的安卓手机瞬间变Firefox os 畅玩firefox os 应用
    新手学JavaScript都要学什么?
    《解读window核心编程》 之 注冊表
    指针知识梳理10-指向数组的指针
    简易迷宫游戏
    CC++控制台颜色设置类
    实用的开放平台整理
    java 集合交并补
    PHP 标准库 SPL 之数据结构栈(SplStack)简单实践
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3595483.html
Copyright © 2011-2022 走看看