码迷,mamicode.com
首页 > 其他好文 > 详细

Two Sum

时间:2015-02-02 21:33:09      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:two sum

link:https://oj.leetcode.com/problems/two-sum/

描述:

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

思路:

先排序O(NlogN),然后两个指针,一个在最前,一个在最后,开始扫描,两个值的和大于target,后面指针往前移动,两个值得和小于target,前面指针往后移动,若和等于target,则是解。

参考代码:

#include <iostream>

#include <vector>

#include <stdio.h>

using namespace std;

struct Node{

    int val;

    int index;

};

bool cmp(Node a,Node b)

{

    return a.val<b.val;

}

vector<int> twoSum(vector<int> &numbers, int target)

{

    vector<int> ret;

    vector<Node> nodeArr;

    for (int i=0; i<numbers.size(); i++) {

        Node item;

        item.val=numbers[i];

        item.index=i+1;

        nodeArr.push_back(item);

    }

    sort(nodeArr.begin(), nodeArr.end(), cmp);

    int start=0;

    int end=(int)numbers.size()-1;

    while (start<nodeArr.size() && end>=0) {

        if (nodeArr[start].val+nodeArr[end].val==target) {

            if (nodeArr[start].index>nodeArr[end].index) {

                ret.push_back(nodeArr[end].index);

                ret.push_back(nodeArr[start].index);

            }else if(nodeArr[start].index<nodeArr[end].index) {

                ret.push_back(nodeArr[start].index);

                ret.push_back(nodeArr[end].index);

            }

            break;

        }else if(nodeArr[start].val+nodeArr[end].val<target){

            start++;

        }else{

            end--;

        }

    }

    return ret;

}


比较笨的算法:

vector<int> twoSum(vector<int> &numbers, int target)

{

    vector<int> ret;

    for (int i=0; i<=numbers.size()/2; i++) {

        for (int j=i+1; j<numbers.size(); j++) {

            if (numbers[i]+numbers[j]==target) {

                ret.push_back(1);

                ret.push_back(2);

                return ret;

            }

        }

    }

    return ret;

}

该算法复杂度是O(N*N)

Two Sum

标签:two sum

原文地址:http://blog.csdn.net/richard_rufeng/article/details/43414169

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!