OJ lintcode 两数之和

给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。
你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 1 到 n,不是以 0 开头。
注意事项
你可以假设只有一组答案。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出 numbers = [2, 7, 11, 15], target = 9, 返回 [1, 2].

/*
class Solution {
public:
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1+1, index2+1] (index1 < index2)
     * 时间 复杂度 O(N^2)
     */
     /*
    vector<int> twoSum(vector<int> &nums, int target) {
        // write your code here
        vector<int> res;
        for(int i=0;i<nums.size();i++){
            for(int j=i+1;j<nums.size();j++){
                if(nums[i]+nums[j]==target){
                    res.push_back(i+1);
                    res.push_back(j+1);
                    return res;
                }
            }
        }

        return res;
    }
};
*/

class Solution {
public:
    /*
    * @param numbers : An array of Integer
    * @param target : target = numbers[index1] + numbers[index2]
    * @return : [index1+1, index2+1] (index1 < index2)
    * 时间复杂度 O(N)
    * 空间复杂度 O(N)
    */
    vector<int> twoSum(vector<int> &nums, int target) {
        // write your code here
        set<int> res;
        
        //构建一个map,实现O(1)的元素查找
        map<int, int > m;
        for (int i = 0; i < nums.size(); i++) {
            int key = nums[i];
            int val = i;
            m[key] = val;
        }

        for (int i = 0; i < nums.size(); i++) {
            int left = target - nums[i];
            auto it=m.find(left);

            if (it != m.end()) {
                int index = i + 1;
                int left_index = m[left] + 1;
                // 排除自身等于自身的情况,比如 这样 [1,0,-1], 0 
                if (index != left_index) {
                    res.insert(index);
                    res.insert(left_index);
                }
            }
        }

        vector<int> ret(res.begin(), res.end());
        return ret;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,353评论 0 33
  • 题目 描述 给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。 你需要实现的函数twoSum需...
    悠扬前奏阅读 3,335评论 0 0
  • Two Sum 题目: Given an array of integers, find two numbers ...
    lyoungzzz阅读 3,060评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,732评论 19 139
  • 几年前一个朋友曾经带我去过一间小众的餐厅。说它小众是因为它不招待walk-in食客,也不接受当天订位。每次我朋友吃...
    187014c5ff96阅读 1,521评论 0 0