首页 > 其他 > 详细

Leetcode[1]-Two Sum

时间:2015-06-09 17:09:32      阅读:191      评论:0      收藏:0      [点我收藏+]

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


分析:
方法一:使用两个for循环,依次比较,不过这个方法在leetcode上超时了

vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> index(2);
    int n = nums.size();
    for(int i = 0; i < n ; i++) {
        index[0] = i+1;
        for(int j = i+1 ; j < n ; j++) {
            if(nums[i] + nums[j] == target){
                index[1] = j+1;
                return index;
            }
        }
    }
    return index;
}

法二:使用map存储所有的数组值和下标值,然后循环在map中找看能否找到target-nums[i]的map,如果找到了就终止循环,没找到继续找;最后返回index数组;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> index(2);
        int n = nums.size();
        map<int,int> mapv;
        for(int i = 0; i < n ; i++) {
            mapv[nums[i]] = i;
        }
        map<int,int>::iterator it = mapv.end();
        for(int i = 0; i < n; i++) {
            it = mapv.find(target - nums[i]);
            if(it != mapv.end() && i!=it->second){
                index[0]=min(i+1, it->second + 1);
                index[1]=max(i+1, it->second + 1);
                break;
            }
        }
        return index;
    }
};

Leetcode[1]-Two Sum

原文:http://blog.csdn.net/dream_angel_z/article/details/46428579

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!