[LeetCode] Two Sum

来源:互联网 发布:苹果最新软件源 编辑:程序博客网 时间:2024/06/03 11:45

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

/*****************************************************************************    *  @COPYRIGHT NOTICE    *  @Copyright (c) 2015, 楚兴    *  @All rights reserved    *  @Version  : 1.0    *  @Author   : 楚兴    *  @Date     : 2015/2/5 13:40    *  @Status   : Accepted    *  @Runtime  : 22 ms*****************************************************************************/#include <iostream>#include <vector>#include <algorithm>using namespace std;class Solution {public:vector<int> twoSum(vector<int> &numbers, int target) {vector<int> indices;vector<int> temp(numbers);sort(numbers.begin(),numbers.end());for (int i = 0; i < numbers.size() - 1; i++){for (int j = i + 1; j < numbers.size(); j++){if (numbers[i] + numbers[j] == target){int n1 = find(temp,numbers[i]);int n2 = find(temp,numbers[j], n1 - 1);if (n1 < n2){indices.push_back(n1);indices.push_back(n2);}else{indices.push_back(n2);indices.push_back(n1);}return indices;}if (numbers[i] + numbers[j] > target){break;}}}}private:int find(vector<int> num, int n, int flag = -1){for (int i = 0; i < num.size(); i++){if (i == flag){continue; //不能和前一个点序号相同}if (num[i] == n){return i + 1;}}}};int main(){vector<int> nums;nums.push_back(2);nums.push_back(7);nums.push_back(11);nums.push_back(14);Solution s;vector<int> indices = s.twoSum(nums,9);return 0;}

// Runtime: 28 msclass Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        unordered_map<int, int> mymap;        vector<int> indices;        for (int i = 0; i < nums.size(); i++)        {            if (mymap.find(target - nums[i]) != mymap.end())            {                indices.push_back(mymap[target-nums[i]] + 1);                indices.push_back(i + 1);            }            else            {                mymap[nums[i]] = i;            }        }        return indices;    }};

0 0