美文网首页
1. Two Sum

1. Two Sum

作者: 白菜炖豆腐 | 来源:发表于2016-05-12 21:52 被阅读0次

题目

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.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

分析

刚看到题目,闪过脑子的第一个想法就是用两层循环进行相加判断,但是,提交之后,超时了。
然后想了好久不知道怎么解决,只能参考别人的代码,用了map,缩短了查找时间,同时改变了每个都相加在和target比对的办法,直接用target减去一个数,然后再找有没有对应的数。
map.count()返回某个元素出现的次数,不是0就是1,因为再map里面不存在等价的两个(以上)元素

代码

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> results;
        
        map<int, int> map; 
        
        for(int i=0;i<nums.size();i++){
            if(!map.count(nums[i])){//不存在才将数添加进map,且用nums的values做key,key做values,方便呢之后通过相减的值来获取key
                map[nums[i]]=i;
            }
            if (map.count(target-nums[i])){
                int n=map[target-nums[i]];
                if (n<i){//防止出现自己加自己的情况 
                    results.push_back(map[target-nums[i]]);
                    results.push_back(i);
                    return results;//题目说只有一种情况,所以直接返回 
                } 
            } 
        } 
        
        return results;        
    }
};

相关文章

  • LeetCode 1. Two Sum (Easy)

    LeetCode 1. Two Sum (Easy) LeetCode 1. Two Sum (Easy) 原题链...

  • 1. Two Sum

    1. Two Sum 题目:https://leetcode.com/problems/two-sum/ 难度: ...

  • leetcode hot100

    1. Two Sum[https://leetcode-cn.com/problems/two-sum/] 字典(...

  • leetCode #1

    #1. Two Sum

  • 1. Two Sum

  • 1. Two Sum

    Given an array of integers, return indices of the two num...

  • 1. Two Sum

    Description Given an array of integers, return indices of...

  • 1. Two Sum

    Problem Given an array of integers, return indices of the...

  • 1. Two Sum

    Given an array of integers, return indices of the two num...

  • 1. Two Sum

    Leetcode: 1. Two SumGiven an array of integers, return in...

网友评论

      本文标题:1. Two Sum

      本文链接:https://www.haomeiwen.com/subject/xkmprttx.html