zoukankan      html  css  js  c++  java
  • LeetCode TwoSum

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            vector<int> ret;
            vector<pair<int, int> > nums;
            for (int i=0; i<numbers.size(); i++) {
                nums.push_back(make_pair(numbers[i], i+1));
            }
            sort(nums.begin(), nums.end());
    
            int i = 0, j = nums.size() - 1;
            int sum = 0;
            while(i<j) {
                sum = nums[i].first + nums[j].first;
                if (sum > target) {
                    j--;
                } else if (sum < target) {
                    i++;
                } else {
                    break;
                }
            }
            ret.push_back(nums[i].second);
            ret.push_back(nums[j].second);
            sort(ret.begin(), ret.end());
            return ret;
        }
    };

    怒刷存在感

    第二轮:

    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

    感觉第一次做的有点粗糙,看了一发答案简洁许多:

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            unordered_map<int, int> n2i;
            int len = numbers.size();
            vector<int> res;
            for (int i=0; i<len; i++) {
                int cur = numbers[i];
                if (n2i.count(target - cur) > 0) {
                    res = {n2i[target-cur] + 1, i + 1};
                    return res;
                }
                n2i.insert({cur, i});
            }
            return res;
        }
    };
  • 相关阅读:
    Silverlight 4 新特性之NotificationWindow
    如何理解JavaScript原型
    惹恼程序员的十件事
    浅谈HTTP中Get与Post的区别
    asp中Access与Sql Server数据库区别总结
    SQL208语句
    jQuery源码分析
    3. 在 as 和 强制类型转换之间,优先使用 as 操作符。
    揭秘10项必学的.NET技术
    如何设置远程访问SQL Server2005
  • 原文地址:https://www.cnblogs.com/lailailai/p/3615042.html
Copyright © 2011-2022 走看看