LeetCode题解 || Two Sum问题

question:

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

思路:

输入一个无序数组和一个目标和,求出两个数之和为这个目标数的下标,有大小之分。

目前想到三种方法:

(1)暴力枚举法

遍历整个数组,测试target与该数的差是否也在数组中,如果在,则这两个数就是要找的,求出其下标即可。

时间复杂度为O(N*N),提交时提醒超时,被鄙视了。

(2)借助hashtable

C++ STL中没有可以直接使用的hashtable模板类,可以使用其他库实现的hashtable或者自己写一个。

hashtable可以在O(1)时间复杂度下查找到一个元素,因此利用hashtable实现暴力枚举法,时间复杂度会降低为O(N)

(3)双指针

首先对数组排序,初始时一个指针指向数组第一个元素,另外一个指针指向最后一个元素,如果两数之和大于target,右指针左移,相反,左指针右移。

排序时间复杂度为O(N*lg N),查找时间复杂度为O(N),所以整体时间复杂度为O(N*lg N)

解题:

利用方法3中的思路

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> tmp(numbers.size());//新建一个等大的数组
        vector<int> res;//用于保存结果
        copy(numbers.begin(),numbers.end(),tmp.begin());//复制
        sort(tmp.begin(),tmp.end());//排序
        vector<int>::iterator start=tmp.begin();//左指针
        vector<int>::iterator terminate=tmp.end()-1;//右指针
        while((*start+*terminate)!=target)
        {
           if((*start+*terminate)>target)
              terminate--;
           if((*start+*terminate)<target)
              start++;
        }
        /*如果数组中有两个相同的元素之和为target,那么find()函数找到的是第一个元素,所以要注意*/
        vector<int>::iterator a;
        vector<int>::iterator b;
        if(*start!=*terminate)
        {
             a=find(numbers.begin(),numbers.end(),*start);
             b=find(numbers.begin(),numbers.end(),*terminate);
        }
        else
        {
            a=find(numbers.begin(),numbers.end(),*start);
            b=find(a+1,numbers.end(),*terminate);//第二次查找起点不一样
        }
       res.push_back(a-numbers.begin()+1);
       res.push_back(b-numbers.begin()+1);
       sort(res.begin(),res.end());
        return res;
    }
};

Submission Result: Accepted

时间: 2024-08-19 10:17:23

LeetCode题解 || Two Sum问题的相关文章

[LeetCode: 题解] Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will

LeetCode题解之 Sum of Left Leaves

1.题目描述 2.问题分析 对于每个节点,如果其左子节点是叶子,则加上它的值,如果不是,递归,再对右子节点递归即可. 3.代码 1 int sumOfLeftLeaves(TreeNode* root) { 2 if (root == NULL) 3 return 0; 4 int ans = 0; 5 if (root->left != NULL) { 6 if (root->left->left == NULL && root->left->right =

[LeetCode 题解]:Candy

There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies

[LeetCode] 039. Combination Sum (Medium) (C++)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 039. Combination Sum (Medium) 链接: 题目:https://leetcode.com/problems/combination-sum/ 代码(github):https://github.com/illuz/leetcode 题意: 给出一些正整数集合,以及一个目标数,从集合中选择一

[leetcode] 040. Combination Sum II (Medium) (C++)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 040. Combination Sum II (Medium) 链接: 题目:https://leetcode.com/problems/combination-sum-ii/ 代码(github):https://github.com/illuz/leetcode 题意: 跟 039 一样(给出一些正整数集合,

&lt;LeetCode OJ&gt; 129. Sum Root to Leaf Numbers

Total Accepted: 74843 Total Submissions: 229553 Difficulty: Medium Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Fin

[LeetCode] 001. Two Sum (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 001.Two_Sum (Medium) 链接: 题目:https://oj.leetcode.com/problems/two-sum/ 代码(github):https://github.com/illuz/leetcode 题意: 一个数组中两个位置上的数的和恰为 target,求这两个位置. 分析: 暴力找

(leetcode题解)Pascal&#39;s Triangle

Pascal's Triangle  Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 题意实现一个杨辉三角. 这道题只要注意了边界条件应该很好实现出来,C++实现如下 vector<vector<int>> generate(int

LeetCode --- 1. Two Sum

题目链接: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. Plea